- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to sort an ArrayList in Descending Order in Java
To sort an ArrayList, you need to use the Collections.sort() method. This sorts in ascending order, but if you want to sort the ArrayList in descending order, use the Collections.reverseOrder() method as well. This gets included as a parameter −
Collections.sort(myList, Collections.reverseOrder());
Following is the code to sort an ArrayList in descending order in Java −
Example
import java.util.ArrayList; import java.util.Collections; public class Demo { public static void main(String args[]) { ArrayList<Integer> myList = new ArrayList<Integer>(); myList.add(30); myList.add(99); myList.add(12); myList.add(23); myList.add(8); myList.add(94); myList.add(78); myList.add(87); System.out.println("Points
"+ myList); Collections.sort(myList,Collections.reverseOrder()); System.out.println("Points (descending order)
"+ myList); } }
Output
Points [30, 99, 12, 23, 8, 94, 78, 87] Points (descending order) [99, 94, 87, 78, 30, 23, 12, 8]
Let us see another example wherein we will sort string values in descending order −
Example
import java.util.ArrayList; import java.util.Collections; public class Demo { public static void main(String args[]) { ArrayList<String> myList = new ArrayList<String>(); myList.add("Jack"); myList.add("Katie"); myList.add("Amy"); myList.add("Tom"); myList.add("David"); myList.add("Arnold"); myList.add("Steve"); myList.add("Tim"); System.out.println("Names
"+ myList); Collections.sort(myList,Collections.reverseOrder()); System.out.println("Names (descending order)
"+ myList); } }
Output
Names [Jack, Katie, Amy, Tom, David, Arnold, Steve, Tim] Names (descending order) [Tom, Tim, Steve, Katie, Jack, David, Arnold, Amy]
Advertisements
To Continue Learning Please Login
Login with Google