I am trying to sort my list of objects like this:
List<UsersDataFoundTo> mergedUsers = mergeUsersFound(ldapUsers, foundUsers);
return mergedUsers.sort((UsersDataFoundTo h1, UsersDataFoundTo h2) -> h1.getLastName().compareTo(h2.getLastName()));
and on the return statement I get an error:
Incompatible types.
Required: java.util.List<UsersDataFoundTo>
Found:void
What do I do wrong then?
Much easier would be to write is as:
mergedUsers.sort(Comparator.comparing(UsersDataFoundTo::getLastName))
And sort
has a void
return type, so basically do a :
return mergedUsers;
For reusable, I think the class UsersDataFoundTo should implements Comparable and override compareTo function.
class UsersDataFoundTo implements Comparable<UsersDataFoundTo> {
private String lastNam;
public String getLastNam() {
return lastNam;
}
public void setLastNam(String lastNam) {
this.lastNam = lastNam;
}
@Override
public int compareTo(UsersDataFoundTo other) {
return getLastNam().compareTo(other.getLastNam());
}
}
Then you can use a collection utility to sort it like this:
List<UsersDataFoundTo> mergedUsers = //...
java.util.Collections.sort(mergedUsers);
I hope this help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.