Sorting objects within a Set by a String value that all objects contain

后端 未结 7 985
北荒
北荒 2021-01-01 01:30

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

7条回答
  •  醉酒成梦
    2021-01-01 02:20

    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 {
      ...
      @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.

提交回复
热议问题