What is the "good" (and why ?) solution to get a List
from a Set
and sorted against a given Comparator
?
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.
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.
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.
Set<Object> set = new HashSet<Object>();
// add stuff
List<Object> list = new ArrayList<Object>(set);
Collections.sort(list, new MyComparator());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With