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:43

With Java 8 you have several options, combining method references and the built-in comparing comparator:

import static java.util.Comparator.comparing;

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

Collections.sort(list, comparing(CustomObject::getId));
//or
list.sort(comparing(CustomObject::getId));
查看更多
登录 后发表回答