96
How to Sort Java ArrayList in Descending Order
By using Collections.reverseOrder(Comparator<T>cmp) method, we can sort the collection in reverse order. The reverseOrder() method does the reversing on the basis of given Comparator. In case of null, it will reverse collection in natural ordering.
Let’s see a simple example to sort the ArrayList in descending order.
SmartPhone.java
ArrayListLearning.java
Output:
Actual List [SmartPhone [brand=Apple, model=6s, price=50000, rating=10], SmartPhone [brand=lg, model=pro2, price=40000, rating=9], SmartPhone [brand=MI, model=3s, price=10000, rating=6], SmartPhone [brand=Letv, model=le2, price=12000, rating=7]] Sorting the list as comparator [SmartPhone [brand=MI, model=3s, price=10000, rating=6], SmartPhone [brand=Letv, model=le2, price=12000, rating=7], SmartPhone [brand=lg, model=pro2, price=40000, rating=9], SmartPhone [brand=Apple, model=6s, price=50000, rating=10]] Reversing the Comparator sorting Printing the reverse list [SmartPhone [brand=Apple, model=6s, price=50000, rating=10], SmartPhone [brand=lg, model=pro2, price=40000, rating=9], SmartPhone [brand=Letv, model=le2, price=12000, rating=7], SmartPhone [brand=MI, model=3s, price=10000, rating=6]]
Next TopicJava Collections Interview Questions