Comparator is not working, I can't fing mistake

2110 views java

I'm trying to sort list of objects fetched from database with comparator object. It should compare last names and if last names are the same it should compare first names and determinate order by them, so if I have list like that:

[Jon Doe] [Zed Adams] [John Adams]

It should be sorted like that:

[John Adams] [Zed Adams] [Jon Doe]

Now let's take a look at my code:

Comparator class:

public class ComparatorContactByName implements Comparator<Contact> {

public int compare(Contact c1, Contact c2) {

    // if lastNames of compared objects are not the same, compare them
        return c1.getLastName().compareTo(c2.getLastName());

    // if lastNames are the same, compare by firstName
    }else if(c1.getLastName().toLowerCase().equals(c1.getLastName().toLowerCase())){
        return c1.getFirstName().toLowerCase().compareTo(c2.getFirstName().toLowerCase());

        // other case like firstName and lastName are the same, compare by id
        return c1.getContactId() - c2.getContactId();


Controller Method:

public void getAllContactsSortedByName(){

    List<Contact> allContacts = ContactRepository.listAllContacts();

    Comparator comparatorContactByName = new ComparatorContactByName();

    Collections.sort(allContacts, comparatorContactByName);

    if (allContacts == null) {
        System.out.println("No contact found. ");
    } else {
        for (Contact contact : allContacts) {


After calling this method I'm getting output like this:

Contact{contactId= 133, firstName= John, lastName= Adams, email=, groups= [gym]}

Contact{contactId= 126, firstName= Jon, lastName= Doe, email=, groups= [work, gym]}

Contact{contactId= 130, firstName= Zed, lastName= Adams, email=, groups= [work]}

"Zed" should be second, but he is last. Any ideas how to fix this logic?

answered question

In Java 8+: Comparator.comparing(Contact::getLastName).thenComparing(Con‌​cat::getFirstName).t‌​henComparingInt(Cont‌​act::getConcatId).

In "c1.getLastName().toLowerCase().equals(c1.getLastName().toLo‌​werCase())": you're using c1 twice. And use c1.getLastName().equalsIgnoreCase(c2.getLastName()), anyway.

in compare() your if statements compare c1 with c1 rather than comparing c1 with c2.

2 Answers


Use Comparator API:

 Comparator<Contact> comparator = Comparator.comparing(Contact::getLastName)

posted this

this is what u have done:


you are comparing c1's last name with c1's last name

instead do this:


same goes for first name!

posted this

Have an answer?


Please login first before posting an answer.