我正在尝试使用比较器对象对从数据库中获取的对象列表进行排序。它应该比较 last names 并且如果 last names 相同它应该比较 first names 并确定它们的顺序,所以如果我有这样的列表那:
[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();
}
}
}
Controller 方法:
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”应该排在第二位,但他却排在最后。有什么想法可以解决这个逻辑吗?
最佳答案
这就是你所做的:
c1.getLastName().toLowerCase().equals(c1.getLastName().toLowerCase()
你正在比较c1的的姓氏和c1的的姓氏
改为这样做:
c1.getLastName().toLowerCase().equals(c2.getLastName().toLowerCase()
名字也一样!
关于java - 比较器不工作,我找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53215968/