如何使用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()) ));
可选调整方案
- 如果你需要指定生成的List具体实现(比如指定为
ArrayList),可以将内层的Collectors.toList()替换为Collectors.toCollection(ArrayList::new) - 如果你需要指定生成的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 ));
- 如果原始List中可能存在
null的MyVO实例,可以在map操作前添加.filter(Objects::nonNull)避免空指针异常
注意:如果没有手动编写getName()方法,使用Lombok的@Data/@Getter注解也可以自动生成该方法,保证方法引用可正常编译
内容的提问来源于stack exchange,提问作者sonic boom
相关产品推荐
相关产品推荐

