Calling NavigableSet.subSet() can do what you want. NavigableSet is a sorted set that has the ability to create subsets that are βviewsβ of the base set. These views are limited to the values ββyou provide using the Comparator provided when you created the set, or the natural order of the values. The most common version is TreeSet . For example, you can do this:
NavigableSet<String> set = new TreeSet<>( Arrays.asList("b", "e", "a", "d", "c")); System.out.println(set);
The result is [a, b, c, d, e] , as you expected. Now you can create a subset, for example, from "b" to "d" inclusive:
NavigableSet<String> set2 = set.subSet("b", true, "d", true); System.out.println(set2);
Here is the conclusion [b, c, d] . Now, if you add some elements to the original set that are both inside and outside the borders, changes in the subset will include only what was added inside:
set.add("a1"); set.add("c1"); set.add("e1"); System.out.println(set2);
Output signal [b, c, c1, d] .
source share