Hi All
I have a generic Collection and am trying to work out how I can sort the items contained within it. Ive tried a few things but I cant get any of them working.
Hi All
I have a generic Collection and am trying to work out how I can sort the items contained within it. Ive tried a few things but I cant get any of them working.
You can't if T is all you get. You have to have the it injected by the provider via:
Collection<T extends Comparable>
or pass in the Comparator via the Collections.sort(...) method
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()
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
You have two basic options provided by java.util.Collections
:
<T extends Comparable<? super T>> void sort(List<T> list)
T implements Comparable
and you're fine with that natural ordering<T> void sort(List<T> list, Comparator<? super T> c)
Comparator
.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);