Java流LambdaExp ForEach_

Java流LambdaExp ForEach_,java,arraylist,lambda,foreach,java-stream,Java,Arraylist,Lambda,Foreach,Java Stream,我不明白为什么它不工作,打印时没有+“a” publicstaticvoidmain(字符串[]args){ List stringi=new ArrayList(); 字符串a=“gg”; 字符串a2=“hf”; 字符串a3=“wp”; i.加入(a); (i)加入(a2); (i)加入(a3); stringi.stream().forEach((x)->x.concat(“str”); stringi.forEach((s)->{ 系统输出打印项次; }); } 它不像您所想的那样工作,在

我不明白为什么它不工作,打印时没有
+“a”

publicstaticvoidmain(字符串[]args){
List stringi=new ArrayList();
字符串a=“gg”;
字符串a2=“hf”;
字符串a3=“wp”;
i.加入(a);
(i)加入(a2);
(i)加入(a3);
stringi.stream().forEach((x)->x.concat(“str”);
stringi.forEach((s)->{
系统输出打印项次;
});
}

它不像您所想的那样工作,在您的代码中concat是无用的,因为您不会在任何对象中存储串联的结果

要获得正确的结果,可以将第一个forEach替换为map,然后再替换为for each,例如:

stringi.stream()
        .map(x -> x.concat("str"))
        .forEach(System.out::println);
或者,您可以在列表中收集结果,然后打印每个元素:

List<String> result = stringi.stream()
        .map(x -> x.concat("str"))
        .collect(Collectors.toList());
result.forEach(System.out::println);

这不起作用,因为JAVA中的sring是不可变的。因此,当执行
x.concat(“str”)
时,它基本上会在内存中创建一个新字符串,第一个字符串的内容为
ggstr
,以此类推。但是列表
stringi
仍然有字符串的引用
gg
等等。

请发布代码,而不是code.ty的图像,它
s工作,但我的列表是不会改变的。其次,它是我想要的,tnx你这个人。@Arsendmitriev如果你想改变初始列表,那么
stringi=stringi.stream().map(x->x.concat(“str”).collect(Collectors.toList());
rly-tnx,我浪费了两个小时,读了关于流的书,等等。你让我度过了美好的一天。
List<String> result = stringi.stream()
        .map(x -> x.concat("str"))
        .collect(Collectors.toList());
result.forEach(System.out::println);
stringi = stringi.stream()
        .map(x -> x.concat("str"))
        .collect(Collectors.toList());