1

我想创建一个通用test()函数来演示Stream操作allMatchanyMatchnoneMatch。它可能看起来像这样(无法编译):

import java.util.stream.*;
import java.util.function.*;

public class Tester {
    void test(Function<Predicate<Integer>, Boolean> matcher, int val) {
        System.out.println(
            Stream.of(1,2,3,4,5).matcher(n -> n < val));
    }
    public static void main(String[] args) {
        test(Stream::allMatch, 10);
        test(Stream::allMatch, 4);
        test(Stream::anyMatch, 2);
        test(Stream::anyMatch, 0);
        test(Stream::noneMatch, 0);
        test(Stream::noneMatch, 5);
    }
}

(我认为)我的挑战是定义matcher哪个可能需要是通用的,而不是我在这里做的方式。我也不确定是否可以拨打我在此处显示的电话main()

我什至不确定这是否可以做到,所以我会很感激任何见解。

4

1 回答 1

4

以下作品:

static void test(
      BiPredicate<Stream<Integer>, Predicate<Integer>> bipredicate, int val) {
    System.out.println(bipredicate.test(
         IntStream.rangeClosed(1, 5).boxed(), n -> n < val));
}

public static void main(String[] args) {
    test(Stream::allMatch, 10);
    test(Stream::allMatch, 4);
    test(Stream::anyMatch, 2);
    test(Stream::anyMatch, 0);
    test(Stream::noneMatch, 0);
    test(Stream::noneMatch, 5);
}

...但是如果重点是演示这些事情的作用,那么您最好写得更直接

System.out.println(IntStream.rangeClosed(1, 5).allMatch(n -> n < 10));

..etcetera,这更容易阅读。

于 2015-11-12T21:55:01.637 回答