SortedSetset = new TreeSet<>(); set.add("apple"); set.add("banana"); set.add("peach"); set.add("orange"); System.out.println(set); // [apple, banana, orange, peach]
SortedSetIn this example, a SortedSet of Integers is created using a TreeSet with a Custom Comparator that sorts elements in descending order. Elements are added to the set and printed to the console. The output shows that the elements are stored in descending order according to the Custom Comparator.set = new TreeSet<>(Comparator.reverseOrder()); set.add(10); set.add(5); set.add(20); set.add(15); System.out.println(set); // [20, 15, 10, 5]