Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
Mercer Avatar asked Mar 19 '10 12:03

Mercer


1 Answers

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 
like image 91
Alexander Pogrebnyak Avatar answered Oct 15 '22 11:10

Alexander Pogrebnyak