过滤流直到谓词

时间:2015-10-05 16:54:03

标签: java java-8 java-stream

我有一个Java 8对象流,我想在匹配给定谓词后忽略这些对象。

示例:我希望将所有字符串保持在" BREAK"一个(包括它)。

public List<String> values = Arrays.asList("some", "words", "before", "BREAK", "AFTER");

@Test
public void testStopAfter() {
    Stream<String> stream = values.stream();
    //how to filter stream to stop at the first BREAK
    //stream = stream.filter(s -> "BREAK".equals(s));
    final List<String> actual = stream.collect(Collectors.toList());

    final List<String> expected = Arrays.asList("some", "words", "before", "BREAK");
    assertEquals(expected, actual);
}

因为它失败(预期:&lt; [some,words,before,BREAK]&gt;但是:&lt; [some,words,before,BREAK,AFTER]&gt;)如果我取消注释过滤器,我只会得到&#34; BREAK&#34;

我正在考虑一个有状态的Predicate(请参阅下面的答案),但如果有更好的解决方案,我会徘徊?

1 个答案:

答案 0 :(得分:0)

使用statefull谓词,在给定谓词匹配之前回答true,然后使用false。

[...]
stream = stream.filter(makeUntil(s -> "BREAK".equals(s)));
[...]


public static <T> Predicate<T> makeUntil(final Predicate<T> predicate) {
    return new Predicate<T>() {

        private boolean hasMatched;

        @Override
        public boolean test(final T s) {
            if (hasMatched) {
                return false;
            }
            else {
                hasMatched = predicate.test(s);
                return true;
            }
        }

    };
}