I'm interested in what criteria are used to sort Set when converting? And how can this be overridden? Because, as I understand it, Set does not store sorting information. An example of the conversion I'm talking about:
Set<Object> objectsSet = new HashSet<>();
Objects[] objectsArray = (Objects[]) objectsSet.toArray();
Not sorted. LinkedHashSet
preserves insertion order; HashSet
is going to be ordered by the hashCode()
internally. If you want a sorted Set
, use a TreeSet
(which implements SortedSet
).
SortedSet<Object> objectsSet = new TreeSet<>();
Objects[] objectsArray = (Objects[]) objectsSet.toArray();
As for changing the order (ascending or descending), you can use TreeSet(Comparator<? super E> comparator)
when constructing the Set
. For example, to sort integers in reverse order;
SortedSet<Integer> intSet = new TreeSet<>(Comparator.reverseOrder());
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