When you create an
ArrayList in Java, elements are stored in the order they are inserted. By default, iterating over the list will display
items in this insertion order. However, in real-world applications you often need to sort an ArrayList in Java, whether
alphabetically, numerically, or by custom rules such as dates or objects.
In this tutorial, we’ll explore how to sort ArrayList in Java using different approaches available in Java. We’ll cover sorting
Strings, Integers, and Dates in both ascending and descending order.
Options for sorting a List
Java provides multiple ways to sort a list:
Using List.sort() (Java 8 and later)
The sort() method was introduced as a default interface method in the List interface. It allows you to sort directly without using external utilities.
list.sort(Comparator.naturalOrder()); // Ascending order
list.sort(Comparator.reverseOrder()); // Descending order
Method signature
default void sort(Comparator<? super E> c)- If the comparator is null, elements must implement Comparable, and natural ordering will be applied.
Using Collections.sort() method
The traditional way to sort an ArrayList is via the Collections utility class. There are two overloaded versions of sort method and according to Java docs their description is-
- public static <T extends Comparable<? super T>> void sort(List<T> list)-
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements
in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually
comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
- public static <T> void sort(List<T> list, Comparator<? super T> c)- Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).
Usage-
Collections.sort(list); // Natural ascending order
Collections.sort(list, Comparator.reverseOrder()); // Custom order
Using Java Stream API
Using sorted method of the
Java Stream API which provides a functional approach to sorting, especially useful when you want a sorted view without modifying the original list. There are two overloaded variants of the sorted method.
- sorted()- Returns a stream consisting of the elements of this stream, sorted according to natural order.
- sorted(Comparator<? super T> comparator)- Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
Sorting ArrayList of strings using sort() method of List
public class SortListDemo {
public static void main(String[] args) {
List<String> cityList = new ArrayList<>();
cityList.add("Delhi");
cityList.add("Mumbai");
cityList.add("Bangalore");
cityList.add("Chennai");
cityList.add("Kolkata");
cityList.add("Mumbai");
// Passing null so natural ordering is used
cityList.sort(null);
System.out.println("List sorted using natural ordering" + cityList);
// Using naturalOrder method to sort in natural order
cityList.sort(Comparator.naturalOrder());
System.out.println("List sorted using natural ordering" + cityList);
// Using reverseOrder method to impose reverse of natural ordering
cityList.sort(Comparator.reverseOrder());
System.out.println("List sorted in reverse" + cityList);
}
}
Output
List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse[Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]
Using Collections.sort() method to sort ArrayList
To sort an ArrayList of strings according to the natural ordering of its elements we can use the first of the two sort methods.
Collections.sort(List<T> list)
public class SortListDemo {
public static void main(String[] args) {
List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
// sorting the list
Collections.sort(cityList);
System.out.println("List sorted using natural ordering" + cityList);
}
}
Output
List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
As you can see you just need to pass the ArrayList to sort method. Collections.sort will work in this case
because String class
implements Comparable interface and provides implementation for the method compareTo(String anotherString).
Same way Integer class or Date class also implements Comparable interface so list of integers (or dates) can also be sorted in
natural order by using sort() method of the Collections class or by using sort() method of the List interface. In fact Java docs give a list of all the classes that
implements comparable interface thus can be used with the sort method to sort the elements in the natural order.
Classes Implementing Comparable
Following is the list of classes that already implement Comparable interface in Java. Thus the ArrayList storing obejcts of any of these classes can be sorted in its natural ordering by passing the list to sort() method.
| Class |
Natural Ordering |
| Byte |
Signed numerical |
| Character |
Unsigned numerical |
| Long |
Signed numerical |
| Integer |
Signed numerical |
| Short |
Signed numerical |
| Double |
Signed numerical |
| Float |
Signed numerical |
| BigInteger |
Signed numerical |
| BigDecimal |
Signed numerical |
| Boolean |
Boolean.FALSE < Boolean.TRUE |
| File |
System-dependent lexicographic on path name |
| String |
Lexicographic |
| Date |
Chronological |
| CollationKey |
Locale-specific lexicographic |
Sorting an ArrayList of strings in descending order
Collections.sort() method always sorts ArrayList of strings in ascending order. For sorting an
ArrayList in descending order you need to use the second sort method which takes two parameters.
First is the list that has to be sorted and second a comparator class that can be used to allow precise control
over the sort order.
For sorting an ArrayList in descending order there are two options,
Sorting ArrayList in descending order using reverseOrder method
public class SortListDemo {
public static void main(String[] args) {
List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
// sorting the list in descending order
Collections.sort(cityList, Collections.reverseOrder());
System.out.println("List sorted in reverses order- " + cityList);
}
}
Output
List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]
Sorting ArrayList in descending order using custom Comparator
Internally reverseOrder method calls a Comparator class to sort the list in reverse order. We can do it
ourselves too by writing our own comparator class.
public class SortListDemo {
public static void main(String[] args) {
List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
// sorting the list in descending order
Collections.sort(cityList, (String a, String b)-> b.compareTo(a));
System.out.println("List sorted in reverses order- " + cityList);
}
}
Output
List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]
Note that Comparator is implemented as a lambda expression here.
Sorting Java ArrayList using sorted method of the Java Stream
public class SortListDemo {
public static void main(String[] args) {
List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
List<String> tempList = cityList.stream().sorted().collect(Collectors.toList());
System.out.println("List sorted in natural order- " + tempList);
tempList = cityList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println("List sorted in reverse order- " + tempList);
}
}
Output
List sorted in natural order- [Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]
That's all for this topic How to Sort ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
-
How ArrayList Works Internally in Java
-
How to Join Lists in Java
- How to Remove Duplicate Elements From an ArrayList in Java
-
Difference Between Comparable and Comparator in Java
-
Java Collections Interview Questions And Answers
You may also like-
-
Fail-Fast Vs Fail-Safe Iterator in Java
-
How to Iterate a HashMap of ArrayLists of String in Java
-
static import in Java
-
Interface Static Methods in Java
-
Method Reference in Java
-
Count Number of Times Each Character Appears in a String Java Program
-
Java ThreadLocal Class With Examples
-
Try-With-Resources in Java With Examples