Sorting an ArrayList of Objects alphabetically

The sorting part can be done by implementing a custom Comparator<Vehicle>.

Collections.sort(vehiclearray, new Comparator<Vehicle>() {
    public int compare(Vehicle v1, Vehicle v2) {
        return v1.getEmail().compareTo(v2.getEmail());
    }
});

This anonymous class will be used for sorting the Vehicle objects in the ArrayList on the base of their corresponding emails alphabetically.

Upgrading to Java8 will let you also implement this in a less verbose manner with a method reference:

Collections.sort(vehiclearray, Comparator.comparing(Vehicle::getEmail));

Leave a Comment