Reputation: 47
I need to place objects User in the collection, and then sort them by three Comparators. Thus sorted collection must pass a variable. What a collection to choose? How to implement it?
ArrayList<User> list2 = Collections.sort(list , new NameComparator());
So it is impossible. Can I use TreeSet or ArrayList ?
public class User {
private String name;
private String surname;
private String login;
}
public class NameComparator implements Comparator<User>{
public int compare(User a, User b){
return a.getName().compareTo(b.getName());
}
}
public class SurnameComparator implements Comparator<User>{
public int compare(User a, User b){
return a.getSurname().compareTo(b.getSurname());
}
}
public class LoginComparator implements Comparator<User>{
public int compare(User a, User b){
return a.getLogin().compareTo(b.getLogin());
}
}
How to do it?
TreeSet set1= new TreeSet<User>(new NameComparator());
set1.add(new User("RRRR","TTTT","KK"));
set1.add(new User("AAA","EEEEE","QQQQ"));
set1.add(new User("GGGG","BBBBB","ssss"));
set1.add(new User("BBBB","BBBBF","AAAA"));
System.out.println(set1);
TreeSet set2= new TreeSet<User>( new LoginComparator());
set2=set1;
System.out.println(set2);
Upvotes: 0
Views: 62
Reputation: 91
You can use the ArrayList collection, but elements are not automatically ordered after every insertion (unless you invoke again an explicit sorting). To achieve this you have to use TreeSet (or a ConcurrentSkipListSet).
To use ArrayList you can simply do:
ArrayList<User> myList = new ArrayList<>();
myList.add(new User());
myList.add(new User());
myList.add(new User());
// Add your elements.
Collections.sort(myList , new LoginComparator());
Collections.sort(myList , new SurnameComparator());
Collections.sort(myList , new NameComparator());
Consider also that the method Collections.sort(...)
does not returns a new instance, it's a void method. In your first line you were assigning the result of sort to a new ArrayList.
Upvotes: 1
Reputation: 159
You can use the TreeSet collection. While creating the TreeSet just pass the class of the Comparator u want.
For Example: Set<User> userSet=new TreeSet<User>(new NameComparator());
This will order your set based on the name.
Upvotes: 0