Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an ArrayList of Objects alphabetically

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");  } 
like image 763
Fluxxxy Avatar asked Oct 19 '13 20:10

Fluxxxy


People also ask

How can you sort an ArrayList of objects?

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.

Does ArrayList have a sort method?

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.

How do you sort elements in an ArrayList using comparable interface?

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.


1 Answers

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)); 
like image 176
Konstantin Yovkov Avatar answered Sep 21 '22 02:09

Konstantin Yovkov