How to sort an ArrayList in Ascending Order in Java

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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\n"+ myList);
      Collections.sort(myList);
      System.out.println("Points (ascending order)\n"+ 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

 Live Demo

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\n"+ myList);
      Collections.sort(myList);
      System.out.println("Student Names (ascending)\n"+ myList);
   }
}

Output

Student Names
[Tim, John, Steve, Andy, Devillers, Jacob, Franco, Amy]
Student Names (ascending)
[Amy, Andy, Devillers, Franco, Jacob, John, Steve, Tim]
raja
Published on 20-Sep-2019 10:21:14
Advertisements