Mercer Mercer - 5 months ago 16
Java Question

How to sort a Collection<T>?

I have a generic

and am trying to work out how I can sort the items contained within it. I've tried a few things but I can't get any of them working.


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