userbb
userbb

Reputation: 1874

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?

Upvotes: 5

Views: 1311

Answers (1)

Stuart Marks
Stuart Marks

Reputation: 132390

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

Upvotes: 3

Related Questions