Sorting objects within a Set by a String value tha

2019-02-10 13:25发布

Ok this is a tricky one. I have a list of Sets. I would like to sort the objects in the Sets in an order.

Imagine each set as repressenting a class in a school. Each set contains person objects. A person object holds a String value for name. I'd like to arrange the Persons in the Set by name before I loop through and write them out.

Is there anywahy to use Collections.sort(); or something similar to achieve this?

for (Set<Person> s : listOfAllChildren) {       
      for (Person p : s) {
        if(p.getClass().equalsIgnoreCase("Jones")){
          System.out.println(p.getName());
          }
         else if...//carry on through other classes 
        }                              
      }        

I do know that 2+ children in a class may share the same name but please ignore this

7条回答
对你真心纯属浪费
2楼-- · 2019-02-10 14:06

Yes! This you can definitely use Collection.sort(). But you will need to either use a sorted set (like TreeSet). Or, alternatively, you can first insert all the elements in the Set to a List.

Then, your Person class needs to implement Comparable, as this interface will be called by the Collections.sort() when it tries to decide in which order to place them. So it can be something simple like:

public class Person implements Comparable<Person> {
  ...
  @Override
  public int compareTo(Person p) {
    return this.name.compareTo(p.name);
  }
}

If using a TreeSet, it should be sorted already. Otherwise, if using a List, simply call Collections.sort(List l) on each list.

查看更多
登录 后发表回答