Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ascending and Desending order in same program using java

I want to sort the data according to id and marks pair. ID should be in ascending order and marks should be in descending order, here is my code:

ArrayList<Student> al=new ArrayList<Student>();
    al.add(new Student(1,"dg",58));
    al.add(new Student(2,"dg",48));
    al.add(new Student(1,"dg",98));
    al.add(new Student(2,"dg",68));
    al.add(new Student(1,"dg",38));
    al.add(new Student(2,"dg",28));
    al.add(new Student(2,"dg",90));    

output like:

1 dg 98  
1 dg 58  
1 dg 38  
2 dg 90  
2 dg 68  
2 dg 48  
2 dg 28  
like image 404
codenow123 Avatar asked Dec 05 '18 10:12

codenow123


People also ask

How do you do ascending and descending order in Java?

We can sort arrays in ascending order using the sort() method which can be accessed from the Arrays class. The sort() method takes in the array to be sorted as a parameter. To sort an array in descending order, we used the reverseOrder() method provided by the Collections class.

How do you arrange numbers in descending order in Java?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.

How do you put numbers in ascending order in Java?

out. print("Numbers in Ascending Order:" ); for(int i = 0; i < arr. length; i++) { Arrays. sort(arr); System.


1 Answers

You have to implement Comparable for the Student class or sort it directly using a custom Comparator:

Comparator<Student> comparator = Comparator
    .comparing(Student::getId)                            // First ID in ascending order
    .thenComparing(Comparator.comparing(Student::getMark) // Then mark 
                             .reversed());                // ... but in descending order

al.sort(comparator);                                      // Here is the sort performed
like image 153
Nikolas Charalambidis Avatar answered Nov 04 '22 21:11

Nikolas Charalambidis