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));
Although the question already has an accepted answer I would like to share some Java 8 solution
// if you only want to sort the list of Vehicles on their email address
Collections.sort(list, (p1, p2) -> p1.getEmail().compareTo(p2.getEmail()));
.
// sort the Vehicles in a Stream
list.stream().sorted((p1, p2) -> p1.getEmail().compareTo(p2.getEmail()));
.
// sort and print with a Stream in one go
list.stream().sorted((p1, p2) -> p1.getEmail().compareTo(p2.getEmail())).forEach(p -> System.out.printf("%s%n", p));
.
// sort with an Comparator (thanks @Philipp)
// for the list
Collections.sort(list, Comparator.comparing(Vehicle::getEmail));
// for the Stream
list.stream().sorted(Comparator.comparing(Vehicle::getEmail)).forEach(p -> System.out.printf("%s%n", p));