如何从Guava RangeSet获得包容性结果?

时间:2018-05-07 20:22:16

标签: java range guava

ImmutableRangeSet<Integer> rangeSet1 = ImmutableRangeSet.of(Range.closed(1, 10));
ImmutableRangeSet<Integer> rangeSet2 = ImmutableRangeSet.of(Range.closed(3, 6));
ImmutableRangeSet<Integer> result = rangeSet1.difference(rangeSet2);

rangeSet1和rangeSet2之差的结果是[[1..3), (6..10]]

但我需要获得包含范围的结果:[[1..2], [7..10]]

1 个答案:

答案 0 :(得分:0)

我的解决方案是从ContiguousSet的每个范围创建RangeSet以转换为封闭范围。

    ImmutableRangeSet<Integer> rangeSet1 = ImmutableRangeSet.of(Range.closed(1, 10));
    ImmutableRangeSet<Integer> rangeSet2 = ImmutableRangeSet.of(Range.closed(3, 6));

    ImmutableRangeSet<Integer> difference = rangeSet1.difference(rangeSet2);
    ImmutableRangeSet<Integer> closedRangeSet = difference.asRanges().stream()
            .map(range -> {
                DiscreteDomain<Integer> domain = DiscreteDomain.integers();
                return ContiguousSet.create(range, domain).range(BoundType.CLOSED, BoundType.CLOSED);
            })
            .collect(Collectors.collectingAndThen(toSet(), ImmutableRangeSet::copyOf));

    System.out.println(closedRangeSet);