Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get subSet of set by using comparator

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?

like image 513
userbb Avatar asked Oct 18 '22 16:10

userbb


1 Answers

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

like image 146
Stuart Marks Avatar answered Oct 29 '22 02:10

Stuart Marks