3 回答

TA贡献1911条经验 获得超7个赞
Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));
sort
yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));
说明:
Comparator<T>
int compare(T o1, T o2)
Collections.sort(contacts, new Comparator<Contact>() { public int compare(Contact one, Contact other) { return one.getAddress().compareTo(other.getAddress()); }});
Collections.sort(contacts, (Contact one, Contact other) -> { return one.getAddress().compareTo(other.getAddress());});
参数类型(Java将根据方法签名推断它们) 或 {return
...}
(Contact one, Contact other) -> { return one.getAddress().compareTo(other.getAddress();}
(one, other) -> one.getAddress().compareTo(other.getAddress())
Comparator
comparing(FunctionToComparableValue)
comparing(FunctionToValue, ValueComparator)
Collections.sort(contacts, Comparator.comparing(Contact::getAddress)); //assuming that Address implements Comparable (provides default order).

TA贡献1943条经验 获得超7个赞
使你 Contact
类实现 Comparable
界面 创建方法 public int compareTo(Contact anotherContact)
在里面。 一旦你这么做了,你就可以打电话 Collections.sort(myContactList);
,哪里 myContactList
是 ArrayList<Contact>
(或任何其他收集 Contact
).
public class Contact implements Comparable<Contact> { .... //return -1 for less than, 0 for equals, and 1 for more than public compareTo(Contact anotherContact) { int result = 0; result = getName().compareTo(anotherContact.getName()); if (result != 0) { return result; } result = getNunmber().compareTo(anotherContact.getNumber()); if (result != 0) { return result; } ... }}
添加回答
举报