我有一个包含布尔字段的类用户,我想对用户列表进行排序,我希望布尔字段等于 true 的用户位于列表的顶部,并且我想按名称对它们进行排序。
这是我的课程:
public class User{
int id;
String name;
boolean myBooleanField;
public User(int id, String name, boolean myBooleanField){
this.id = id;
this.name = name;
this.myBooleanField = myBooleanField;
}
@Override
public boolean equals(Object obj) {
return this.id == ((User) obj).id;
}
}
这是一个例子来明确我想要什么:
假设我有这样的用户集合:
ArrayList<User> users = new ArrayList<User>();
users.add(new User(1,"user1",false));
users.add(new User(2,"user2",true));
users.add(new User(3,"user3",true));
users.add(new User(4,"user4",false));
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
//Here i'm lookin for what should i add to compare the two users depending to the boolean field
return u1.name.compareTo(u2.name);
}
});
for(User u : users){
System.out.println(u.name);
}
我想对用户进行排序以获得此结果:
user2
user3
user1
user4
你可以使用Boolean.compare(boolean x, boolean y)
方法第一。自从true
元素被排序到数组的开头,您可以使用compare(u2.myBooleanField, u1.myBooleanField)
:
@Override
public int compare(User u1, User u2) {
final int booleanCompare = Boolean.compare(u2.myBooleanField,
u1.myBooleanField);
if (booleanCompare != 0) {
return booleanCompare;
}
return u1.name.compareTo(u2.name);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)