Sorting an ArrayList of Person with java collections
Collections.sort(List<T>)
method expects the element of the list it is sorting to be comparable. Either the element type T
should implement the Comparable
interface, or you should use the overloaded sort()
method, that takes a generic Comparator
instance.
In the code below, you are satisfying neither of the above conditions. Neither your Person
class implements Comparable
, nor you are passing any Comparator
instance.
ArrayList<Person> nameFromText = new ArrayList<Person>();
fillArrayList(nameFromText, pullFile);
// Sort ArrayList
Collections.sort(nameFromText); // How to sort?
You should create a Comparator
for your Person
class to tell the sort()
method how to sort it (may be on String stored in Person class)
Here's how you implement a generic comparator:
public class PersonNameComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
And then your Collections.sort()
method invocation should be like: -
Collections.sort(nameFromText, new PersonNameComparator());
Alternatively you can implement Comparable interface directly in Person class and override 'compareTo(Object obj) ' method. In this case you would not need to create new class for comparator. And this behaves like inbuilt sorting.
Try this:
List<String> inputString = Arrays.asList("Sijan", "Sudeep", "Parasar", "Raj Kumar");
Collections.sort(inputString);
System.out.println(inputString);