我有ArrayList
有两个字符串和一个Integer
,但我只需要按字符串Name
和字符串LastName
对其进行排序,我试过了像这样的方法Collections.sort
Collections.sort(MyArrayList, (Contact v1, Contact v2) -> v1.getName().compareTo(v2.getname()));
但是这只是通过名称对ArrayList
进行排序,并且不包括姓氏,我如何添加姓氏的排序?
答案 0 :(得分:3)
为比较器使用Comparator.comparing(Contact::getName).thenComparing(Contact::getLastName)
:
Collections.sort(MyArrayList, Comparator.comparing(Contact::getName).thenComparing(Contact::getLastName));
答案 1 :(得分:2)
您只需要更改比较功能以包含其他字段
Collections.sort(contacts, (Contact c1, Contact c2) -> {
int firstNameComparisonResult = c1.getFirstName().compareTo(c2.getFirstName());
if (firstNameComparisonResult != 0) {
return firstNameComparisonResult;
} else {
return c1.getLastName().compareTo(c2.getLastName());
}
});
警告:这假定没有空值。
我想用的完整代码:
class Contact{
final String firstName;
final String lastName;
final int age;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public Contact(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
@Override
public String toString() {
return "Contact{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
'}';
}
}
@Test
public void sortTest(){
List<Contact> contacts = new ArrayList<>();
contacts.add(new Contact("A","B",37));
contacts.add(new Contact("A","C",34));
contacts.add(new Contact("B","A",35));
Collections.sort(contacts, (Contact c1, Contact c2) -> {
int firstNameComparisonResult = c1.getFirstName().compareTo(c2.getFirstName());
if (firstNameComparisonResult != 0) {
return firstNameComparisonResult;
} else {
return c1.getLastName().compareTo(c2.getLastName());
}
});
System.out.println(contacts);
//[Contact{firstName='A', lastName='B', age=37}, Contact{firstName='A', lastName='C', age=34}, Contact{firstName='B', lastName='A', age=35}]
}
答案 2 :(得分:0)
嗯...将你的闭包变成一个完整的匿名类,并利用这种力量来增加你的排序复杂性......
像
这样的东西 Collections.sort(MyArrayList, new Comparator<Contact>() {
public int compare(Contact v1, Contact v2) {
int returned = v1.getvName().compareTo(v2.getname())
if(returned==0) {
// alas, Math.signum returns a float value in this cas
returned = (int) Math.signum(v1.getYourInt(), v2.getYourInt())
}
return returned;
}
});
警告此代码尚未以任何方式编译。