Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
how to generate the array contains random number in ascending order using java

I would like to make the array contains random number in ascending order, for example (1,5,10...100), but not (5,1,10...). this code but when run the number not be ascending . what the error?

     Random r=new Random();
     int t=10;
       int a[]=new int[t];
     int count=0;
     int end=0;
     int curr=0;
     while(count<t){
     curr=r.nextInt();
     end=end+curr;
     count++;}
     for(int i=0;i<to;i++){
     a[i]=r.nextInt(10);}
 ```
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use the Random#ints method which returns a stream of random int values. Assuming you want 10 random ints from the range [1,100) sorted in ascending order:

Random r = new Random();
int t    = 10;
int a[]  = r.ints(1, 100).distinct().limit(t).sorted().toArray();
System.out.println(Arrays.toString(a));

you can omit distinct if you want to allow duplicates

To sort in descending order you need to box the primitiv types to Integer and use Comparator.reverseOrder() or Collections.reverseOrder() and unbox them after sorting to store them in an int array

int a[]  = r.ints(0, 100)
                .distinct()
                .limit(t)
                .boxed()
                .sorted(Comparator.reverseOrder())
                .mapToInt(Integer::intValue)
                .toArray();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!