Java sort via bucket value
Am trying to sort via a certain value in the function,
Collection users = roster.getEntries();
if(!users.isEmpty()) {
Iterator userIterator = users.iterator();
while(userIterator.h开发者_如何学CasNext()) {
String name = user.getName()==null?user.getUser():user.getName();
Now before iterating, I want to sort this Collection by the user's name. Any suggestions on how to go about this?
Thank you for your time.
You can use Collections.sort() and provide a Comparator, provided the collection preserves order. If it doesn't copy it into an ArrayList.
Unless you are using Java 1.4 or older I would use generics and the for-each loop.
Collection<User> users = roster.getEntries();
if(!users.isEmpty()) {
Collections.sort(users, SORT_BY_NAME_COMPARATOR);
for(User user: users) {
// do something
}
}
Consider you have a User class. That class could implement Comparable. Read about this interface and the usage.
Or you can simply try it by applying anonymous Comparator
class
Collections.sort( users , new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ( (User)o1 ).getName().compareTo( ( (User)o2 ).getName() );
}
});
精彩评论