按Set属性的大小比较对象,在排序列表的末尾留下空Set

时间:2018-02-19 13:02:10

标签: java enums compare comparator

public class User {

    private String name;
    private  private Set<MyEnum> enums;

    //getter and setter methods..
}

public enum MyEnum {

    A(1, "..."),
    B(2, "...");

    private int value;
    private String description;

    private MyEnum(int value, String description){
        ....
    }
}

如何比较两个用户实例,先按枚举属性再按名称进行比较? 当我们有一个枚举集而不是单个值时,它是可能的吗?

1 个答案:

答案 0 :(得分:2)

编辑:按枚号设置大小排序,然后按名称排序。保留用户的空枚举:

我实现了自定义Comparator

class UserComparator implements Comparator<User> {
  @Override
  public int compare(User u1, User u2) {
    int compResult = Integer.compare(u1.getEnums().size(), u2.getEnums().size());
    if(compResult == 0)
      compResult = u1.getName().compareTo(u2.getName());
    return compResult;
  }

然后使用List sort(Comparator c)方法:

User u1 = new User();
u1.setName("Sarah");
u1.setEnums(Collections.emptySet());
User u2 = new User();
u2.setName("Bob");
u2.setEnums(Collections.emptySet());
User u3 = new User();
u3.setName("Peter");
u3.setEnums(EnumSet.of(MyEnum.A, MyEnum.B));
User u4 = new User();
u4.setName("Nicolas");
u4.setEnums(EnumSet.of(MyEnum.A, MyEnum.B));
User u5 = new User();
u5.setName("Paul");
u5.setEnums(EnumSet.of(MyEnum.A));

List<User> users = Arrays.asList(u1, u2, u3, u4, u5);
users.sort(new UserComparator());

// Then split the list and move the users with empty enums at the end
List<User> sortedNonEmptySetUsers = users.stream()
    .filter(u -> !u.getEnums().isEmpty())
    .collect(Collectors.toList());
List<User> sortedEmptySetUsers = users.stream()
    .filter(u -> u.getEnums().isEmpty())
    .collect(Collectors.toList());
sortedNonEmptySetUsers.addAll(sortedEmptySetUsers);

List<User> sortedUsers = sortedNonEmptySetUsers;

以这种方式订购

Paul | [A]
Nicolas | [B, A]
Peter | [B, A]
Bob | []    
Sarah | []