How to sort a Collection<T>?
Collections by themselves do not have a predefined order, therefore you must convert them to
a java.util.List
. Then you can use one form of java.util.Collections.sort
Collection< T > collection = ...;
List< T > list = new ArrayList< T >( collection );
Collections.sort( list );
// or
Collections.sort( list, new Comparator< T >( ){...} );
// list now is sorted
A Collection
does not have an ordering, so wanting to sort it does not make sense. You can sort List
instances and arrays, and the methods to do that are Collections.sort()
and Arrays.sort()
You have two basic options provided by java.util.Collections
:
-
<T extends Comparable<? super T>> void sort(List<T> list)
- Use this if
T implements Comparable
and you're fine with that natural ordering
- Use this if
-
<T> void sort(List<T> list, Comparator<? super T> c)
- Use this if you want to provide your own
Comparator
.
- Use this if you want to provide your own
Depending on what the Collection
is, you can also look at SortedSet
or SortedMap
.
If your collections object is a list, I would use the sort method, as proposed in the other answers.
However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:
TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);