I have a class user which contains a boolean field, I want to sort a list of users, I want the users who have the boolean field equals true to be in the top of the list and than I want sort them by their names. Here is my class :
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;
}
}
Here is an example to clear what I want : lets say that I have this collection of users :
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);
}
I want to sort users to get this result :
user2
user3
user1
user4
You could use the Boolean.compare(boolean x, boolean y)
method first. And since true
elements are sorted to the beginning of the array, you would use 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);
}
Something along these lines perhaps?
Collections.sort(users, new Comparator<User>() {
public int compare(User u1, User u2) {
String val1 = (u1.myBooleanField ? "0" : "1") + u1.name;
String val2 = (u2.myBooleanField ? "0" : "1") + u2.name;
return val1.compareTo(val2);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With