Q: How to sort an instance of
See a more detailed explanation
here.
java.util.Set
?
A:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Set<String> set = new HashSet<>(); List<String> list = new ArrayList<>(); list.addAll(set); Collections.sort(list); // sorted by insertion order Set<String> sortedSet = new LinkedHashSet<>(); sortedSet.addAll(list); // sorted by natural ordering of elements (need to implement Comparable) // or by given Comparator Set<String> sortedTreeSet = new TreeSet<>(); // we can add the unsorted set, will be sorted automatically each time // when modifying sortedTreeSet.addAll(set); |