如何使用Java 8 Stream API将ElementCharacteristic列表转为Map<String,String>
使用Java Stream API实现列表转Map
完整实现代码(与原for循环行为完全一致)
public Map<String,String> getMap(List<ElementCharacteristic> inputList) { return inputList.stream() .collect(Collectors.toMap( ElementCharacteristic::getCharacteristic, ElementCharacteristic::getFeature, (oldValue, newValue) -> newValue // 处理重复key,保留新值,和原循环覆盖逻辑一致 )); }
关键说明
- 调用
inputList.stream()将列表转换为Stream对象,开启流式操作 Collectors.toMap()是核心收集器,负责将流元素映射为Map:- 第一个参数:
ElementCharacteristic::getCharacteristic,指定Map的key来源,对应原代码中put方法的第一个参数 - 第二个参数:
ElementCharacteristic::getFeature,指定Map的value来源,对应原代码中put方法的第二个参数 - 第三个参数:合并函数
(oldValue, newValue) -> newValue,当遇到重复key时,用新值覆盖旧值,和原for循环的行为完全匹配。如果省略这个参数,当流中存在重复key时会直接抛出IllegalStateException
- 第一个参数:
简化版(适用于无重复key的场景)
如果能保证输入列表中不会出现重复的characteristic值,可省略合并函数,代码更简洁:
public Map<String,String> getMap(List<ElementCharacteristic> inputList) { return inputList.stream() .collect(Collectors.toMap( ElementCharacteristic::getCharacteristic, ElementCharacteristic::getFeature )); }
内容的提问来源于stack exchange,提问作者Andulos
相关产品推荐
相关产品推荐

