Java8 generate a map, it has key from each item in a list and it has value from a pair for that list

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;
    }
}

I want to generate a Map<Integer, Integer> map based on the above enum, which has key from each element in types and value from that types‘s code.

This is map (k,v) from A:

(0, 1)
(1, 1)
(2, 1)
(3, 1)
(100, 1)
(101, 1)
This is from B:
(4,2)

This is what I am current stuck at:

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

>Solution :

You can use flatMap for this purpose

Map<Integer, Integer> result = Arrays.stream(MyEnum.values())
                .flatMap(myEnum -> myEnum.getTypes().stream().map(type -> new AbstractMap.SimpleEntry<>(type, myEnum.getCode())))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

enter image description here

Leave a Reply