Reputation: 11
So I get some names from user input and put them into a list that references class Person.
Class person has constructors with getters
public String getName(){
return email;
}
But is also has setters with the exceptions so they can't insert a blank or improper name.
public void setFullName(String fullName) throws ValidationException{
validateString(fullName);
this.fullName = fullName;
}
But as it is based on user input, I have x amount of names. What I'm wanting to do is organize them alphabetically so that the first in the list won't necessarily be the first name I entered.
Here is the List and ArrayList that is in a constructor
private List<Person> peopleList;
public Contacts(){
peopleList = new ArrayList<Person>();
}
I already know that I can't do
List<Person> subList = peopleList.subList(1, peopleList.size());
Collections.sort(subList);
Because I get "The method sort(List) in the type Collections is not applicable for the arguments (List)" from the Collections.sort
I can't implement a comparable or anything because it won't properly inherit an abstract method from class Person.
So how do I organize the list I have without implementation? If possible.
Upvotes: 0
Views: 74
Reputation: 2102
You should implement a custom comparator first
private Comparator<Person> alphabetical = new Comparator<Person>() {
@Override
public int compare(Person left, Person right) {
return left.getName().compareTo(right.getName());
}
}
Then you can use the Collections.sort() method with 2 arguments
Collections.sort(peopleList, alphabetical);
Or since Java 8 you can use a Lambda
Collections.sort(people list, (left, right) -> left.getName().compareTo(right.getName()));
Upvotes: 0
Reputation: 1465
You can do something like that
class ComparatorPerson implements Comparator<Person>{
public int compare(Person p1, Person p2){
return p1.getFullName().compareTo(p2.getFullName());
}
}
puis
Collections.sort(subList, new ComparatorPerson());
Upvotes: 0
Reputation: 31648
You don't have to modify the Person
class to make it implement Comparable
.
Instead you can write your own Comparator
implementation which has the comparison method compare(a, b)
http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
Collections.sort() has an overloaded version which takes the collection and comparator implementation to use.
public class NameCompartor implements Comparator<Person>{
@Override
public int compare(Person p1, Person p2) {
// TODO Auto-generated method stub
return p1.getFullName().compareTo(p2.getFullName());
}
}
Collections.sort(personList, new NNameCompartor());
Also, I'm not sure why you are taking a subList. Your sublist is skipping the first element (indexes are 0 based)
Upvotes: 0
Reputation: 21004
Functional programming is your friend :
Collections.sort(peopleList, (Person p1, Person p2) -> p1.getFullName().compareTo(p2.getFullName()));
Upvotes: 1