Search code examples
javasortingcollectionsjava-8comparator

Comparator is not working, I can't find the mistake


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> {
    @Override
    public int compare(Contact c1, Contact c2) {

        // if lastNames of compared objects are not the same, compare them
        if(!c1.getLastName().toLowerCase().equals(c1.getLastName().toLowerCase())){
            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
        }else{
            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) {
            System.out.println(contact.toString());
        }
    }
}

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

Contact{contactId= 133, firstName= John, lastName= Adams, email= ja@email.com, groups= [gym]}    
Contact{contactId= 126, firstName= Jon, lastName= Doe, email= jd@email.com, groups= [work, gym]}    
Contact{contactId= 130, firstName= Zed, lastName= Adams, email= za@email.com, groups= [work]}

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


Solution

  • this is what u have done:

    c1.getLastName().toLowerCase().equals(c1.getLastName().toLowerCase()
    

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

    instead do this:

    c1.getLastName().toLowerCase().equals(c2.getLastName().toLowerCase()
    

    same goes for first name!