Sorting in Descending order using Comparator

Your two ternary conditional operators produce the same result (since you swapped both > with < and -1 with 1):

return o1.age > o2.age ? 1 :(o1.age < o2.age ? -1 : 0); //Sorted in Ascending
return o1.age < o2.age ? -1 :(o1.age > o2.age ? 1 : 0); // Not sorted in Descending

For descending order you need :

return o1.age > o2.age ? -1 :(o1.age < o2.age ? 1 : 0);

@Eran already pointed out the error in your comparator.

I'd like to add that you may just return o1.age - o2.age. The result of comparison does not have to be exactly -1 or 1 for < or > it may be just negative or positive.

And you could have also called Comparator.reversed. Or Comparator.comparing(Student::getAge).reversed().

Tags:

Java

Sorting