Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get List from Set and Comparator

What is the "good" (and why ?) solution to get a List from a Set and sorted against a given Comparator ?

like image 932
Manuel Selva Avatar asked Oct 13 '10 12:10

Manuel Selva


People also ask

How do you sort a list of objects based on an attribute of the objects in Java?

sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.

Can we cast set to list in Java?

Using Java 8 Stream: In Java 8, Stream can be used convert a set to a list by converting the set to a sequential Stream using Set. stream() and using a Collector to collect the input elements into a new List.

How do I use Comparator in collections sort?

Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else. Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator.


1 Answers

Set<Object> set = new HashSet<Object>();

// add stuff

List<Object> list = new ArrayList<Object>(set);
Collections.sort(list, new MyComparator());
like image 82
Tyler Treat Avatar answered Sep 20 '22 05:09

Tyler Treat