You need to enable JavaScript to run this app. Java Stream API 如何实现HashMap同键值逗号分隔存储并解决重复键报错
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 19:36:05