Sort Java Collection

2019-01-01 09:11发布

I have a Java collection:

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

CustomObject has an id field now before display list I want to sort this collection by that id.

Is there any way I could that do that?

13条回答
何处买醉
2楼-- · 2019-01-01 09:17

Implement the Comparable interface on your customObject.

查看更多
君临天下
3楼-- · 2019-01-01 09:18

Use sort.

You just have to do this:

All elements in the list must implement the Comparable interface.

(Or use the version below it, as others already said.)

查看更多
大哥的爱人
4楼-- · 2019-01-01 09:20
大哥的爱人
5楼-- · 2019-01-01 09:23

You can use java Custom Class for the purpose of sorting.

查看更多
梦醉为红颜
6楼-- · 2019-01-01 09:24

Use a 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);

Additionally, if CustomObjectimplements Comparable, then just use Collections.sort(list)

With JDK 8 the syntax is much simpler.

List<CustomObject> list = getCustomObjectList();
Collections.sort(list, (left, right) -> left.getId() - right.getId());
System.out.println(list);

Much simplier

List<CustomObject> list = getCustomObjectList();
list.sort((left, right) -> left.getId() - right.getId());
System.out.println(list);

Simplest

List<CustomObject> list = getCustomObjectList();
list.sort(Comparator.comparing(CustomObject::getId));
System.out.println(list);

Obviously the initial code can be used for JDK 8 too.

查看更多
与君花间醉酒
7楼-- · 2019-01-01 09:28

You can also use:

Collections.sort(list, new Comparator<CustomObject>() {
    public int compare(CustomObject obj1, CustomObject obj2) {
        return obj1.id - obj2.id;
    }
});
System.out.println(list);
查看更多
登录 后发表回答