2

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?

3
  • 8
    sort has no return value. Commented Jan 29, 2019 at 9:38
  • 1
    As @Eran says, sort it, and then return the list. Commented Jan 29, 2019 at 9:39
  • Possible duplicate of incompatible types found : void, what is wrong? Commented Jan 29, 2019 at 9:46

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

And if he changes his mind and try to compare on another property UsersDataFoundTo !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.