比较器无法正常工作,我找不到错误

时间:2018-11-08 20:53:29

标签: java sorting comparator

我正在尝试使用比较器对象对从数据库中获取的对象列表进行排序。它应比较姓氏,如果姓氏相同,则应比较名字并按其确定顺序,因此如果我有类似

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

应该这样排序:

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

现在让我们看一下我的代码:

比较器类:

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();
        }
    }
}

控制器方法:

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());
        }
    }
}

调用此方法后,我将得到如下输出:

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”应该排第二,但他排在最后。任何想法如何解决此逻辑?

2 个答案:

答案 0 :(得分:4)

这就是你所做的:

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

您正在将 c1的姓与 c1的

相反,这样做:

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

名字一样!

答案 1 :(得分:1)

使用Comparator API:

 Comparator<Contact> comparator = 
       Comparator.comparing(Contact::getLastName, String.CASE_INSENSITIVE_ORDER)
                 .thenComparing(Concat::getFirstName, String.CASE_INSENSITIVE_ORDER)
                 .thenComparingInt(Contact::getContactId);