hhrzc
hhrzc

Reputation: 2050

How to convert enum with attribute to map using java8 stream

I have an enum:

public enum SheetRows{
    totalActive("Total active");

    String value;

    SheetRows(String value){
        this.value = value;
    }

    public String getValueForTable() {
        return value;
    }
}

How to convert this enum to HashMap<SheetRows, String>?

I try to use:

HashMap<SheetRows, String> cellsMap = Arrays.asList(SheetRows.values()).stream()
            .collect(Collectors.toMap(k -> k, v -> v.getValueForTable()));

but this code isn't compile.

Upvotes: 0

Views: 945

Answers (1)

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

The following should work, the problem is that you're trying to assign a Map to HashMap

Map<SheetRows, String> map = EnumSet.allOf(SheetRows.class)
        .stream()
        .collect(Collectors.toMap(Function.identity(), SheetRows::getValueForTable));

System.out.println("map = " + map); // map = {totalActive=Total active}

If you really need to return a HashMap, you can also use the overload that takes a supplier and a mergeFunction like hereunder.

The mergeFunction will never be called since your enums are unique, so just choose a random one.

HashMap<SheetRows, String> map = EnumSet.allOf(SheetRows.class)
        .stream()
        .collect(Collectors.toMap(Function.identity(), SheetRows::getValueForTable, (o1, o2) -> o1, HashMap::new));

System.out.println("map = " + map); // map = {totalActive=Total active}

Upvotes: 2

Related Questions