使用方法主体的Java 8谓词仅被调用一次? [英] Java 8 predicates using methods bodies are called only once?

查看:53
本文介绍了使用方法主体的Java 8谓词仅被调用一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了以下代码段:

I have examined the following snippet:

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,但这不是我现在关心的问题.

This code is not mine. I know that using a ConcurrentMap is not the right choice in this example and I should use ConcurrentMap instead of Map in this case, but this is not my concern now.

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

I thought that the distinctByKey method is called or interpreted in each iteration of the Stream. I mean the Map being instantiated in each turn, but it's not!

Predicate方法的主体是否仅被调用过一次?

Is the body of the Predicate method called only once?

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

In the Stream iteration, is this an assertion?

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

Because when I try the following code:

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"));

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

I can see that the body of the method is indeed called in each line. What makes the body of the filter to only be called once?

推荐答案

调用.filter(distinctByKey(Function.identity()))时,将评估传递给filter()的参数.这是唯一执行distinctByKey(Function.identity())并返回Predicate<String>实例的时间.

When you call .filter(distinctByKey(Function.identity())), the argument passed to filter() is evaluated. That's the only time distinctByKey(Function.identity()) is executed and returns an instance of Predicate<String>.

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

That Predicate is then evaluated (i.e. it's test() method is executed) multiple times, each time for a different element of the Stream.

要使您的最后一个片段的行为类似于Stream管道,应如下所示:

To make your last snippet behave similar to the Stream pipeline, it should look like this:

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"));

这篇关于使用方法主体的Java 8谓词仅被调用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆