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 it sorting it. I have researched it and tried using Collections.sort(vehiclearray);
but that didn't work for me. I was that I needed something called a comparator but couldn't figure out how it worked. Will I have to use those or can something like bubble sort or insertion sort work for this kind of thing?
This is the code that I have so far:
public static void printallsort(ArrayList<vehicle> vehiclearray){ ArrayList<vehicle> vehiclearraysort = new ArrayList<vehicle>(); vehiclearraysort.addAll(vehiclearray); //Sort for(int i = 0; i < vehiclearraysort.size(); i++) if ( vehiclearray.get(i).getEmail() > vehiclearray.get(i+1).getEmail()) //Printing for(i = 0; i < vehiclearraysort.size(); i++) System.out.println( vehiclearraysort.get(i).toString() + "\n"); }
In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.
An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.
We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With