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
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.
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.
out. print("Numbers in Ascending Order:" ); for(int i = 0; i < arr. length; i++) { Arrays. sort(arr); System.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With