Java ArrayList sort() Method Example

ArrayList Methods with Examples


Java ArrayList Examples


ArrayList sort() method sorts the list according to the order induced by the specified Comparator instance. All elements in the list must be mutually comparable.

Java ArrayList sort() Method Example

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

// Sort an ArrayList using Collections.sort() method.
// Sort an ArrayList using ArrayList.sort() method.
// Sort an ArrayList of user defined objects with a custom comparator.

public class ArrayListSortExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Tony");
        names.add("Tom");
        names.add("Johnson");
        names.add("John");
        names.add("Ramesh");
        names.add("Sanjay");
        
        System.out.println("Names : " + names);

        // Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method.
        names.sort(new Comparator<String>() {
            @Override
            public int compare(String name1, String name2) {
                return name1.compareTo(name2);
            }
        });

        // The above `sort()` method call can also be written simply using lambda expression
        names.sort((name1, name2) -> name1.compareTo(name2));

        // Following is an even more concise solution
        names.sort(Comparator.naturalOrder());

        System.out.println("Sorted Names : " + names);
    }
}
Output:
Names : [Tony, Tom, Johnson, John, Ramesh, Sanjay]
Sorted Names : [John, Johnson, Ramesh, Sanjay, Tom, Tony]

Reference

Comments