我有一个Java集合:
Collection<CustomObject> list = new ArrayList<CustomObject>();
CustomObject
现在在显示列表之前有一个id
字段,我想按该id
对此集合进行排序。有什么办法可以做到吗?
最佳答案
使用Comparator:
List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
@Override
public int compare(CustomObject left, CustomObject right) {
return left.getId() - right.getId(); // use your logic
}
};
Collections.sort(list, comparator); // use the comparator as much as u want
System.out.println(list);
此外,如果
CustomObject
实现Comparable
,则只需使用Collections.sort(list)
使用JDK 8,语法要简单得多。
List<CustomObject> list = getCustomObjectList();
Collections.sort(list, (left, right) -> left.getId() - right.getId());
System.out.println(list);
更简单
List<CustomObject> list = getCustomObjectList();
list.sort((left, right) -> left.getId() - right.getId());
System.out.println(list);
最简单的
List<CustomObject> list = getCustomObjectList();
list.sort(Comparator.comparing(CustomObject::getId));
System.out.println(list);
显然,初始代码也可以用于JDK 8。