排序Java集合

我有一个Java集合:

Collection<CustomObject> list = new ArrayList<CustomObject>();

CustomObject id现在在显示列表之前有一个字段,我想按此排序此集合id

有什么办法可以做到吗?

回答:

使用比较器:

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。

以上是 排序Java集合 的全部内容, 来源链接: utcz.com/qa/406294.html

回到顶部