在Java Lambda中的中断语句

huangapple go评论73阅读模式
英文:

Interrupted statement in java lambda

问题

我有这段代码

Integer[] i = {1,3,4,6,7,43,2,1};
//创建一个断言
Predicate ini = value -> value > 10;;
//显示-过滤-并打印集合中的值
List sss = Stream.of(i).peek(e -> System.out.println(e)).filter(ini).
peek(value -> System.out.println("过滤后 " + value)).collect(Collectors.toList());
//显示过滤后的列表
System.out.println(sss);

我得到了这个结果

1
3
4
6
7
43
过滤后 43
2
1
[43]

我的问题是为什么在peek语句中间会得到过滤消息?我尝试了不同的IDE,但结果都是一样的。

英文:

I have this code

    Integer[] i = {1,3,4,6,7,43,2,1};
    //create a predicate
    Predicate<Integer> ini = value -> value > 10;;
    //display-filter-and print the values in the collection
    List<Integer> sss =Stream.of(i).peek(e -> System.out.println(e)).filter(ini).
            peek(value -> System.out.println("After filter " + value)).collect(Collectors.toList());
    //display the filtered list
    System.out.println(sss);

And I'm getting this result

1
3
4
6
7
43
After filter 43
2
1 
[43]

My question is why I'm getting the filter message in between in the middle of the peek statement? I tried this in different IDEs but I'm getting the same results.

答案1

得分: 1

为什么你感到惊讶?

你有两个peek()方法调用。第一个在过滤器之前,第二个在过滤器之后。

你的流水线逐个消耗元素(这是通过执行终端操作collect()来实现的)。

消耗流中的一个元素涉及应用第一个peek(),它会打印出元素,然后再应用过滤器。

只有当元素通过过滤器时,才会应用第二个peek(),并打印出"After filter .."。

唯一通过过滤器的元素是43,这导致在消耗时打印出以下内容:

43
After filter 43

只有在稍后才会消耗剩余的元素,并在第一个peek应用于它们时打印出来。

英文:

Why are you surprised?

You have two peek() method calls. The first one is before the filter and the second after the filter.

Your stream pipeline consumes one element at a time (and that takes place as a result of executing the terminal operation collect()).

Consuming an element of your stream involves applying the first peek(), which prints the element, followed by applying the filter.

Only if the element passes the filter, the second peek() is applied, and prints "After filter ..".

The only element that passes the filter is 43, which results in

43
After filter 43

being printed when it is consumed.

Only later the remaining elements are consumed, and printed when the first peek is applied on them.

huangapple
  • 本文由 发表于 2020年4月7日 18:14:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/61077659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定