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.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
Valentyn Hruzytskyi
  • 1,772
  • 5
  • 27
  • 59

1 Answers1

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}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • 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) ? – Sergey Afinogenov Apr 07 '21 at 10:07
  • 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 – Yassin Hajaj Apr 07 '21 at 10:14
  • @SergeyAfinogenov See [this question](https://stackoverflow.com/questions/37055794/does-collectors-toset-always-return-a-hashset-what-is-the-contract) – Yassin Hajaj Apr 07 '21 at 10:15