gpt4 book ai didi

java - 考虑在过滤流创建后添加的列表元素

转载 作者:IT老高 更新时间:2023-10-28 20:52:55 25 4
gpt4 key购买 nike

给定以下代码:

List<String> strList = new ArrayList<>(Arrays.asList("Java","Python","Php"));

Stream<String> jFilter = strList.stream().filter(str -> str.startsWith("J"));

strList.add("JavaScript"); // element added after filter creation
strList.add("JQuery"); // element added after filter creation

System.out.println(Arrays.toString(jFilter.toArray()));

哪个输出:

[Java, JavaScript, JQuery]

为什么 JavaScriptJQuery 是在创建过滤后的流之后添加的,却出现在过滤结果中?

最佳答案

简短回答

您在此之后假设:

Stream<String> jFilter = strStream.filter(str -> str.startsWith("J"));

返回以“J”开头的新元素流,即仅返回 Java。然而这不是的情况;

流是惰性的,即它们不执行任何逻辑,除非终端操作另有说明。

流管道的实际执行从 toArray() 调用开始,由于列表在终端 toArray() 操作开始之前被修改,结果将是 [Java、JavaScript、JQuery].

更长的答案

这里是 documentation 的一部分其中提到了这一点:

For well-behaved stream sources, the source can be modified before the terminal operation commences and those modifications will be reflected in the covered elements. For example, consider the following code:

 List<String> l = new ArrayList(Arrays.asList("one", "two"));
Stream<String> sl = l.stream();
l.add("three");
String s = sl.collect(joining(" "));

First a list is created consisting of two strings: "one"; and "two". Then a stream is created from that list. Next the list is modified by adding a third string: "three". Finally the elements of the stream are collected and joined together. Since the list was modified before the terminal collect operation commenced the result will be a string of "one two three". All the streams returned from JDK collections, and most other JDK classes, are well-behaved in this manner;

关于java - 考虑在过滤流创建后添加的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53896175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com