
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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\n"+ myList); Collections.sort(myList,Collections.reverseOrder()); System.out.println("Points (descending order)\n"+ 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\n"+ myList); Collections.sort(myList,Collections.reverseOrder()); System.out.println("Names (descending order)\n"+ myList); } }
Output
Names [Jack, Katie, Amy, Tom, David, Arnold, Steve, Tim] Names (descending order) [Tom, Tim, Steve, Katie, Jack, David, Arnold, Amy]
- Related Questions & Answers
- How to sort an ArrayList in Java in descending order?
- Sort ArrayList in Descending order using Comparator with Java Collections
- How to sort an ArrayList in Java in ascending order?
- How to sort an ArrayList in Ascending Order in Java
- How to sort TreeSet in descending order in Java?
- C# program to sort an array in descending order
- C program to sort an array in descending order
- Sort an array in descending order using C#
- How to perform descending order sort in MongoDB?
- How to sort List in descending order using Comparator in Java
- 8086 program to sort an integer array in descending order
- Sort MongoDB documents in descending order
- How do you sort an array in C# in descending order?
- How can we sort MySQL output in descending order?
- Sort list elements in descending order in C#
Advertisements