使用方法体的 Java 8 谓词仅被调用一次?

2023-12-02

我检查了以下片段:

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> computed = new ConcurrentHashMap<>();/*IS THIS LINE CALLED ONCE ON STREAM->FILTER NOT MATTER HOW LONG THE STREAM IS*/
    return t -> {return computed.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;};
}

private void test(){
    final long d = Stream.of("JOHN","STEPHEN","ORTIZ","RONDON")
            .filter(distinctByKey(Function.identity()))
            .count();
    System.out.println("d = " + d);
}

这段代码不是我的。我知道使用ConcurrentMap在这个例子中不是正确的选择,我应该使用ConcurrentMap代替Map在这种情况下,但这不是我现在关心的。

我以为distinctByKey方法在每次迭代中被调用或解释Stream。我的意思是Map每回合都被实例化,但事实并非如此!

是身体Predicate方法只调用一次?

In the Stream迭代,这是一个断言吗?

因为当我尝试以下代码时:

final Function<String,Integer>a = (name)->name.length();
System.out.println(distinctByKey(a).test("JOHN"));
System.out.println(distinctByKey(a).test("STEPHEN"));
System.out.println(distinctByKey(a).test("ORTIZ"));
System.out.println(distinctByKey(a).test("RONDON"));

我可以看到该方法的主体确实在每一行中被调用。是什么使得过滤器主体只能被调用一次?


你打电话时.filter(distinctByKey(Function.identity())),参数传递给filter()被评估。这是唯一一次distinctByKey(Function.identity())被执行并返回一个实例Predicate<String>.

That Predicate然后被评估(即它是test()方法被执行)多次,每次针对不同的元素Stream.

为了使你的最后一个片段的行为类似于Stream管道,它应该看起来像这样:

final Function<String,Integer> a = (name)->name.length();
Predicate<String> pred = distinctByKey(a);
System.out.println(pred.test("JOHN"));
System.out.println(pred.test("STEPHEN"));
System.out.println(pred.test("ORTIZ"));
System.out.println(pred.test("RONDON"));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用方法体的 Java 8 谓词仅被调用一次? 的相关文章

随机推荐