0

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.

1
  • 5
    That's because toMap is written to return a Map, not a HashMap. Is that all? Commented Apr 7, 2021 at 9:50

1 Answer 1

2

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}
Sign up to request clarification or add additional context in comments.

3 Comments

I thought @Yassin Hajaj that by default toMap method generates a HashMap, in my Java version 1.8 it calls toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new) in this case it could be casted using (HashMap) ?
Yes it could indeed @SergeyAfinogenov, but there is no guarantee that in the future, the JDK will keep sending a HashMap, this is an implementation detail, and the only thing that matters is the contract / spec
@SergeyAfinogenov See this question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.