SortedSetset = new TreeSet<>(Arrays.asList("apple", "banana", "cherry", "dates", "grapes")); SortedSet subset = set.subSet("banana", "dates"); System.out.println(subset); // [banana, cherry] subset.add("dates"); // adding element to subset System.out.println(set); // [apple, banana, cherry, dates, grapes]
class LengthComparator implements ComparatorPackage Library: The java.util.SortedSet interface is a part of the Java Collections Framework, which is available in the java.util package.{ public int compare(String s1, String s2) { return s1.length() - s2.length(); } } SortedSet set = new TreeSet<>(new LengthComparator()); set.addAll(Arrays.asList("apple", "banana", "cherry", "dates", "grapes")); SortedSet subset = set.subSet("banana", "dates"); System.out.println(subset); // [banana, grapes]