开发者

Java sort via bucket value

开发者 https://www.devze.com 2023-03-22 23:15 出处:网络
Am trying to sort via a certain value in the function, Collection users = roster.getEntries(); if(!users.isEmpty()) {

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() );
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号