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

How can I flat map from an enum list property to the enum itself?

Given the following enum:

@Getter
@AllArgsConstructor
public enum SampleEnum {
    A("aaa", Arrays.asList(1,2,3,4)),
    B("bbb", Arrays.asList(5,6,7,8,9)),
    C("ccc", Arrays.asList(10,11)),
    D("ddd", new ArrayList<>());

    private final String code;
    private final List<Integer> symbols;

    // It does not work on arrays 
    private static final Map<String, SampleEnum> CODE_TO_ENUM_MAP =
            stream(values()).collect(toMap(SampleEnum ::getCode, t -> t));
}

I want to create mapping between each symbol in the list to the enum value.

Expected map: Integer -> SampleEnum

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

1 -> A
2 -> A
3 -> A
4 -> A
5 -> B
6 -> B
7 -> B
8 -> B
9 -> B
10 -> C
11 -> C

How can I create this Map<Integer, SampleEnum>?

>Solution :

Add a pair:

static class EnumWithValue {
    SampleEnum sampleEnum;
    int value;

    public EnumWithValue(SampleEnum sampleEnum, int value) {
        this.sampleEnum = sampleEnum;
        this.value = value;
    }

    public SampleEnum getSampleEnum() {
        return sampleEnum;
    }

    public int getValue() {
        return value;
    }
}

Use flatMap to create int+enum pairs:

private static final Map<Integer, SampleEnum > CODE_TO_ENUM_MAP =
        Arrays.stream(values())
                .flatMap(e -> e.getSymbols().stream().map(symbol -> new EnumWithValue(e, symbol)))
                .collect(Collectors.toMap(EnumWithValue::getValue, EnumWithValue::getSampleEnum));

Executing:

public static void main(String[] args) {
    System.out.println(CODE_TO_ENUM_MAP);
}

Prints:

{1=A, 2=A, 3=A, 4=A, 5=B, 6=B, 7=B, 8=B, 9=B, 10=C, 11=C}
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