Get a subset of a set using a comparator

Is it possible to get a subset of filtering a collection with some comparator and have each update of the parent collection, and its subset get all the changes?

+5
source share
1 answer

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] .

+3
source

Source: https://habr.com/ru/post/1242086/


All Articles