Mercer Mercer - 3 months ago 6
Java Question

How to sort a Collection<T>?

I have a generic

Collection
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.

Answer

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
Comments