You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Java Stream的map()结果添加到ArrayList中?

如何将Stream.map()的结果收集到ArrayList中?

我来帮你解决这个问题,同时给你一些代码优化的建议!

首先,你遇到的核心问题是Stream的惰性求值特性:list.stream().map(n -> n * 3)只是创建了一个包含映射操作的流,但并没有实际执行这个操作,也没有将结果存入mappedList。要把流的结果收集到ArrayList中,你需要使用collect()方法配合合适的收集器。

正确的实现方式

有两种常用写法,根据你的需求选择:

  1. 如果只是需要一个List(不严格要求是ArrayList),可以用Collectors.toList():
List<Integer> mappedList = list.stream()
                               .map(n -> n * 3)
                               .collect(Collectors.toList());
  1. 如果明确需要ArrayList类型(因为toList()返回的List具体实现可能不是ArrayList),可以用Collectors.toCollection()指定容器类型:
List<Integer> mappedList = list.stream()
                               .map(n -> n * 3)
                               .collect(Collectors.toCollection(ArrayList::new));

修改后的完整代码

替换你原来的错误逻辑后,完整代码如下:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        
        while (list.size() < 5) {
            System.out.println("Enter a number for the array: ");
            int num = sc.nextInt();
            list.add(num);
        }
        
        System.out.print("Before mapping: ");
        list.forEach(a -> System.out.print(a + " "));
        System.out.println();
        
        // 正确的映射并收集到ArrayList的写法
        List<Integer> mappedList = list.stream()
                                       .map(n -> n * 3)
                                       .collect(Collectors.toCollection(ArrayList::new));
        
        System.out.print("After mapping: ");
        mappedList.forEach(a -> System.out.print(a + " "));
        
        // 关闭Scanner释放资源
        sc.close();
    }
}

其他代码优化建议

  • 自动关闭资源:推荐使用try-with-resources语法,无需手动调用sc.close(),JVM会自动帮你释放资源:
try (Scanner sc = new Scanner(System.in)) {
    // 所有输入逻辑放在这里
}
  • 健壮的输入校验:如果用户输入非整数内容,sc.nextInt()会抛出异常,添加校验让程序更稳定:
while (list.size() < 5) {
    System.out.println("Enter a number for the array: ");
    if (sc.hasNextInt()) {
        int num = sc.nextInt();
        list.add(num);
    } else {
        System.out.println("Please enter a valid integer!");
        sc.next(); // 消费无效输入,避免死循环
    }
}
  • 简洁的输出方式:可以用Collectors.joining()替代循环打印,代码更整洁:
System.out.printf("Before mapping: %s%n", 
                  list.stream().map(String::valueOf).collect(Collectors.joining(" ")));

内容的提问来源于stack exchange,提问作者Stephen Mbonu Ugochukwu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:42:29