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
.