有人可以解释以下代码的行为吗?特别是为什么流中的 forEach 会更改原始 List?:
import java.util.ArrayList;
import java.util.List;
public class foreachIssue {
class justanInt {
public int anint;
public justanInt(int t){
anint=t;
}
}
public static void main(String[] args){
new foreachIssue();
}
public foreachIssue(){
System.out.println("The Stream Output:");
List<justanInt> lst = new ArrayList<>();
justanInt j1=new justanInt(2);
justanInt j2=new justanInt(5);
lst.add(j1);lst.add(j2);
lst.stream()
.map((s)->{
s.anint=s.anint*s.anint;
return s;
})
.forEach((s)->System.out.println("Anything"));
System.out.println(" lst after the stream:");
for(justanInt il:lst)
System.out.println(il.anint);
List<justanInt> lst1 = new ArrayList<>();
justanInt j3=new justanInt(2);
justanInt j4=new justanInt(5);
lst1.add(j3);lst1.add(j4);
lst1.stream()
.map((s)->{
s.anint=s.anint*s.anint;
return s;
});
System.out.println(" lst1 after the stream without forEach:");
for(justanInt il:lst1)
System.out.println(il.anint);
}
}
输出为:
流输出:
任何东西
任何东西
流后lst:
4
25
没有 forEach 的流之后的 lst1:
2
5
最佳答案
Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.
因此,您提供给 map
的 Function
在您使用 Stream
之前不会应用。在第一种情况下,您可以使用 forEach
来完成此操作。 ,这是一个终端操作。在第二种情况下,你不会。
关于java - 可能是Java1.8流异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27045786/