我想构建一个方法来按第二个名称对列表进行排序,但是如果我有两个具有第二个名称的相似对象,我的方法将仅按名字对相似的对象进行排序。
例如,这是我的列表:
List<Person> p = new ArrayList<Person>();
p.add(new Person("Konrath", "Will"));
p.add(new Person("Pavol","Rower"));
p.add(new Person("Abie", "Backi"));
p.add(new Person("Bartie", "Rower"));
return p;
我想要这样的结果:
List<Person> p = new ArrayList<Person>();
p.add(new Person("Abie", "Backi"));
p.add(new Person("Bartie", "Rower"));
p.add(new Person("Pavol", "Rower"));
p.add(new Person("Konrath","Will"));
return p;
当我的第二个名字(如“Rower”)相同时,此方法按名字排序。
有没有简单的方法可以做到这一点?
最佳答案
您需要使用自定义Comparator
:
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
下面是自 java 1.2 起有效的 Comparator
实现。
从 java 8 开始,可以有更短的实现,正如 Robin Topper 所评论的。
public class SecondThanFirstComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
// Handle nulls
if (p1.getSecondName().equals(p2.getSecondName())) {
return p1.getFirstName().compareTo(p2.getFirstName());
} else {
return p1.getSecondName().compareTo(p2.getSecondName());
}
return 0;
}
}
List<Person> p = ...;
...
Collections.sort(p, new SecondThanFirstComparator());
// From here p list is sorted
关于java - 按第二名对列表进行排序,但如果第二名相同,则按名字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43589594/