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?
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?
As of Java 8 you now can do it with a stream using a lambda:
You should implement the
Comparator
interface.example:
Then you can use the Collections classes
Collections.sort()
method:The question is: "Sort Collection". So you can't use
Collections.sort(List<T> l, Comparator<? super T> comparator)
.Some tips:
For Collection type:
For List type:
For Set type:
Java 8 version. There is
java.util.List#sort(Comparator<? super E> c)
methodor
or for types that implements Comparable:
A slightly different example say if you have a class that doesn't implement Comparable but you still want to sort it on a field or method.
SortedSet and Comparator. Comparator should honour the id field.
A lot of correct answers, but I haven't found this one: Collections cannot be sorted, you can only iterate through them.
Now you can iterate over them and create a new sorted
something
. Follow the answers here for that.