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){
....
}
}
首先如何通过枚举属性,然后用名称比较两个用户实例?当我们有一个枚举集时,可能是可能的,而不是单个值?
编辑:按枚举设置大小进行排序,然后按名称进行排序。为用户留下空的枚举:
我将实现自定义比较器
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;
}
然后使用列表排序(比较器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 | []