Since Java 8+, to sort an ArrayList, you can use its sort(Comparator) method in conjunction with Comparable and Comparator to control over the sort order

  • Using Comparator.comparing or your defined lambda functions to extract a Comparable sort key from the objects you want to sort

  • For the Comparable implemented objects, using Comparator.naturalOrder() to sort in natural order and Comparator.reverseOrder() to sort in reverse order

Sort an ArrayList of strings and numbers

You can use Comparator.naturalOrder() and Comparator.reverseOrder() along with the sort method as String and Number objects such as Integer, Long, Short, Double, Float, Byte are implemented Comparable by default

  • Sort in ascending order
List<Integer> lst1 = new ArrayList<>();  
lst1.add(3);  
lst1.add(1);  
lst1.add(2);  
lst1.sort(Comparator.naturalOrder());  
System.out.println(lst1); // [1, 2, 3]

List<String> lst2 = new ArrayList<>();  
lst2.add("b");  
lst2.add("c");  
lst2.add("a");  
lst2.sort(Comparator.naturalOrder());  
System.out.println(lst2); // [a, b, c]
  • Sort in descending order
List<Integer> lst1 = new ArrayList<>();  
lst1.add(3);  
lst1.add(1);  
lst1.add(2);  
lst1.sort(Comparator.reverseOrder());  
System.out.println(lst1); // [3, 2, 1]

List<String> lst2 = new ArrayList<>();  
lst2.add("b");  
lst2.add("c");  
lst2.add("a");  
lst2.sort(Comparator.reverseOrder());  
System.out.println(lst1); // [c, b, a]  

Sort an ArrayList of objects by field / property

Let's say we have two classes, NonComparableBook without Comparable and ComparableBook with Comparable implementation as below



The above compareTo method provides the default / natural order in ascending to ComparableBook objects by the field title. If you want the default order in descending, try to reverse the operands of compareTo

@Override
public int compareTo(ComparableBook o) {  
    return o.title.compareTo(this.title);
}

The following test cases show you how to sort an ArrayList of NonComparableBook and ComparableBook objects in ascending and descending order of the field title


Troubleshooting

  • ArrayList accepts null elements, however, NullPointerException will be thrown if you try to sort one contained null elements
List<Integer> lst = new ArrayList<>();  
lst.add(3);  
lst.add(1);  
lst.add(2);  
lst.add(null);  
lst.sort(Comparator.naturalOrder()); // throws NullPointerException


Notes

  • You can also use Collection.sort methods to sort a List in Java. They internally call to the specified list's sort method which in turn also dispatches to the Java 8+ sort(Comparator) default method of the List interface


Conclusion

In this tutorial, we learned using ArrayList's sort(Comparator) method as well as with Comparable and Comparator interfaces to sort an ArrayList of strings, numbers and objects