I have to create a method that sorts an ArrayList of objects alphabetically according to email and then prints the sorted array. The part that I am having trouble with
The sorting part can be done by implementing a custom Comparator
.
Collections.sort(vehiclearray, new Comparator() {
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));