To sort an ArrayList in Java, you can use ArrayList instance's sort(Comparator), Collections.sort(List) or Collections.sort(List, Comparator) methods in conjunction with Comparable and Comparator to control over the sort order

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

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

  • Collections.sort methods are internally call to ArrayList instance's sort(Comparator) method which in turn also dispatches to the Java 8+ sort(Comparator) method of List interface

Sort an ArrayList of strings and numbers

You can use Comparator.naturalOrder() and Comparator.reverseOrder() along with the sort methods 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 = Arrays.asList(3, 1, 2);  
lst1.sort(Comparator.naturalOrder());  
System.out.println(lst1); // [1, 2, 3]

List<String> lst2 = Arrays.asList("b", "c", "a");  
Collections.sort(lst2);  
System.out.println(lst2); // [a, b, c]
  • Sort in descending order
List<String> lst1 = Arrays.asList("b", "c", "a");  
lst1.sort(Comparator.reverseOrder());  
System.out.println(lst1); // [c, b, a]

List<Integer> lst2 = Arrays.asList(3, 1, 2);  
Collections.sort(lst2, Comparator.reverseOrder());  
System.out.println(lst2); // [3, 2, 1]  

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



Conclusion

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