Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading