In this tutorial we have shared the examples of sorting an String ArrayList and Integer ArrayList.
Also Read:
Example 1: Sorting of ArrayList<String>
Here we are sorting the ArrayList
of String
type. We are doing it by simply calling the Collections.sort(arraylist)
method. The output List will be sorted alphabetically.
import java.util.*; public class Details { public static void main(String args[]){ ArrayList<String> listofcountries = new ArrayList<String>(); listofcountries.add("India"); listofcountries.add("US"); listofcountries.add("China"); listofcountries.add("Denmark"); /*Unsorted List*/ System.out.println("Before Sorting:"); for(String counter: listofcountries){ System.out.println(counter); } /* Sort statement*/ Collections.sort(listofcountries); /* Sorted List*/ System.out.println("After Sorting:"); for(String counter: listofcountries){ System.out.println(counter); } } }
Output:
Before Sorting: India US China Denmark After Sorting: China Denmark India US
Example 2: Sorting of ArrayList<Integer>
The same Collections.sort()
method can be used for sorting the Integer ArrayList
as well.
import java.util.*; public class ArrayListOfInteger { public static void main(String args[]){ ArrayList<Integer> arraylist = new ArrayList<Integer>(); arraylist.add(11); arraylist.add(2); arraylist.add(7); arraylist.add(3); /* ArrayList before the sorting*/ System.out.println("Before Sorting:"); for(int counter: arraylist){ System.out.println(counter); } /* Sorting of arraylist using Collections.sort*/ Collections.sort(arraylist); /* ArrayList after sorting*/ System.out.println("After Sorting:"); for(int counter: arraylist){ System.out.println(counter); } } }
Output:
Before Sorting: 11 2 7 3 After Sorting: 2 3 7 11
Hi, good article, but will Collections.sort eliminate duplicates in case the list contains any duplicates? If not can you show how to eliminate the duplicates?
Refer this: https://beginnersbook.com/2014/10/how-to-remove-repeated-elements-from-arraylist/
For the main method it is supposed to be (String[] args) not (String args[])
Hello Frank, Both are same.
Great tutorial, even for beginners. Sorted my array immediately.
One question, does .sort retain existing order? This is often relevant. If you have it sorted by one criteria, then sort it by another criteria, do values by the second criteria which are equal still show the initial sort criteria is retained, or is the resulting order random?