Is it possible to get subSet of collection filtering by some comparator and have every update on parent collection and its subsets get all changes?
The NavigableSet.subSet()
call might do what you want. NavigableSet
is a sorted set that has the capability to create subsets that are "views" of the underlying set. These views are bounded by values that you provide, using the Comparator
provided at the set's creation, or the values' natural order. The most common implementation 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'd expect. Now you can create a subset, for example from "b" through "d" inclusive:
NavigableSet<String> set2 = set.subSet("b", true, "d", true);
System.out.println(set2);
Here the output is [b, c, d]
. Now if you add some elements to the original set that are both inside and outside of the bounds, the subset view changes to include only what's been added inside:
set.add("a1");
set.add("c1");
set.add("e1");
System.out.println(set2);
The output is [b, c, c1, d]
.
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