Java Stream API 如何实现HashMap同键值逗号分隔存储并解决重复键报错
异常根因
Collectors.toMap默认重载实现遇到重复键时不会自动合并值,会直接抛出IllegalStateException。你当前代码里Vehicle这个dataType对应两个name值,触发了重复键校验,所以才会报错。
代码修改
完全保留原有过滤、键值提取的逻辑,只需要给toMap补上第三个参数——重复键的合并规则,把同键下的多个名称用逗号拼接就行。
修改后的代码:
Map<String, String> myMap = obj.getAttributes().stream() .filter(entity -> AttributeType.REFERRED.equals(entity.getAttributeType())) .collect(Collectors.toMap( EntityObjectDTO.Attributes::getDataType, e -> e.getName(), // 重复键时拼接两个值 (existValue, newValue) -> existValue + "," + newValue ));
可选优化
如果需要保证Map的键顺序和源集合中元素的顺序完全一致,可以补充第四个参数,指定用LinkedHashMap做底层存储:
Map<String, String> myMap = obj.getAttributes().stream() .filter(entity -> AttributeType.REFERRED.equals(entity.getAttributeType())) .collect(Collectors.toMap( EntityObjectDTO.Attributes::getDataType, e -> e.getName(), (existValue, newValue) -> existValue + "," + newValue, LinkedHashMap::new ));
运行后得到的Map结果完全符合预期:
{Vehicle=name1,name2, Person=name3}
内容的提问来源于stack exchange,提问作者Raj_91
相关产品推荐
相关产品推荐

