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

如何用Java 8 Stream基于MyEnum枚举生成指定键值的Map<Integer, Integer>

问题解决:将枚举的types元素映射到对应code的Map

给定枚举定义

public enum MyEnum {
    A(1, Arrays.asList(0, 1, 2, 3, 100, 101)),
    B(2, Arrays.asList(4));

    private Integer code;
    private List<Integer> types;

    MyEnum(Integer code, List<Integer> types) {
        this.code = code;
        this.types = types;
    }

    // 补充getter方法,确保流中能访问私有属性
    public Integer getCode() {
        return code;
    }

    public List<Integer> getTypes() {
        return types;
    }
}

需求说明

生成一个Map<Integer, Integer>,其中键为每个枚举实例中types列表的元素,值为对应枚举实例的code属性。最终映射关系如下:

(0, 1)、(1, 1)、(2, 1)、(3, 1)、(100, 1)、(101, 1)
(4, 2)

当前卡住的代码

Arrays.stream(MyEnum.values()).collect(Collectors.toMap(???, MyEnum::getCode))

解决方案

直接使用Collectors.toMap无法完成需求——每个枚举实例对应多个types元素,需要先通过flatMap将枚举实例拆分为多组(type, code)键值对,再收集到Map中。完整实现代码如下:

Map<Integer, Integer> typeToCodeMap = Arrays.stream(MyEnum.values())
        .flatMap(en -> en.getTypes().stream()
                .map(type -> new AbstractMap.SimpleEntry<>(type, en.getCode())))
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                // 处理键冲突:若存在重复type,保留第一个匹配的code,可按需修改逻辑
                (existing, replacement) -> existing
        ));

代码说明

  1. flatMap展开:将每个枚举实例转换为其types列表元素与对应code的Entry流,把多对一的枚举关系拆分为多个一对一的键值对Entry。
  2. Collectors.toMap收集:
    • 第一个参数取Entry的key作为Map的键
    • 第二个参数取Entry的value作为Map的值
    • 第三个参数定义键冲突处理逻辑,这里选择保留已存在的值,可根据业务需求调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:45:08