我必须实现一个方法map()
下面接收一个数组列表和一个 Function<T, R>
对象,以及
返回一个数组列表,其中包含将函数应用于给定元素的结果。
以下代码打印 1,2,3
而不是这些数字的平方。为什么代码不起作用?我需要失败的原因而不是正确的解决方案。
import java.util.ArrayList;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Mapper {
public static ArrayList<Integer> map(ArrayList<Integer> nums, Function<Integer, Integer> mapper) {
ArrayList<Integer> result = new ArrayList<>(nums);
result.forEach(e -> e = mapper.apply(e));
return result;
}
public static void main(String [] args){
ArrayList<Integer> nums = IntStream.rangeClosed(1, 3).boxed().collect(Collectors.toCollection(ArrayList::new));
ArrayList<Integer> squares = Mapper.map(nums, z -> z * z);
squares.forEach(System.out::println);
}
}
最佳答案
这是因为 result.forEach(e -> ... )
中的 e
不是对列表元素的引用,而是列表中的整数值。将该行视为与此等效:
for (int e : nums) {
e = e * e;
}
这也不会更新 num
集合中的元素。
关于Java 流 - 无法使用 forEach 修改列表的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61133426/