Mercer Mercer - 1 year ago 96
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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download