- 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 Ascending Order in Java
To sort an ArrayList in ascending order, the easiest way is to the Collections.sort() method. With this method, you just need to set the ArrayList as the parameter as shown below −
Collections.sort(ArrayList)
Let us now see an example to sort an ArrayList un ascending order. Here, we are sorting ArrayList with integer elements −
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(50); myList.add(29); myList.add(35); myList.add(11); myList.add(78); myList.add(64); myList.add(89); myList.add(67); System.out.println("Points
"+ myList); Collections.sort(myList); System.out.println("Points (ascending order)
"+ myList); } }
Output
Points [50, 29, 35, 11, 78, 64, 89, 67] Points (ascending) [11, 29, 35, 50, 64, 67, 78, 89]
Following is another code to sort an ArrayList in ascending order in Java. Here, we are sorting ArrayList with string values −
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("Tim"); myList.add("John"); myList.add("Steve"); myList.add("Andy"); myList.add("Devillers"); myList.add("Jacob"); myList.add("Franco"); myList.add("Amy"); System.out.println("Student Names
"+ myList); Collections.sort(myList); System.out.println("Student Names (ascending)
"+ myList); } }
Output
Student Names [Tim, John, Steve, Andy, Devillers, Jacob, Franco, Amy] Student Names (ascending) [Amy, Andy, Devillers, Franco, Jacob, John, Steve, Tim]
Advertisements
To Continue Learning Please Login
Login with Google