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

如何使用Java 8 Stream将Map<KeyString,List<MyVO>>转为值为name列表的Map

实现方案

假设你已经为MyVO类的name属性添加了public的getName() getter方法,核心实现逻辑如下:

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// originalMap为你的原始Map对象
Map<String, List<MyVO>> originalMap = /* 你的原始Map实例 */;

Map<String, List<String>> targetMap = originalMap.entrySet().stream()
    .collect(Collectors.toMap(
        // 保留原有键不变
        Map.Entry::getKey,
        // 将对应值的List<MyVO>转换为仅保留name属性的List<String>
        entry -> entry.getValue().stream()
            .map(MyVO::getName)
            .collect(Collectors.toList())
    ));

可选调整方案

  1. 如果你需要指定生成的List具体实现(比如指定为ArrayList),可以将内层的Collectors.toList()替换为Collectors.toCollection(ArrayList::new)
  2. 如果你需要指定生成的Map具体实现、或者处理可能的键冲突场景,可以使用toMap的重载方法:
Map<String, List<String>> targetMap = originalMap.entrySet().stream()
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        entry -> entry.getValue().stream()
            .map(MyVO::getName)
            .collect(Collectors.toList()),
        // 键冲突处理逻辑,这里示例为保留旧值,可按需调整
        (oldVal, newVal) -> oldVal,
        // 指定生成的Map实现为HashMap
        HashMap::new
    ));
  1. 如果原始List中可能存在null的MyVO实例,可以在map操作前添加.filter(Objects::nonNull)避免空指针异常

注意:如果没有手动编写getName()方法,使用Lombok的@Data/@Getter注解也可以自动生成该方法,保证方法引用可正常编译

内容的提问来源于stack exchange,提问作者sonic boom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:00:00