Java 8: Transform EnumMap<ExampleEnum, String> to Map<String, Object>

1.6k Views Asked by At

I have a situation where I need to copy my EnumMap<ExampleEnum,String> to Map<String, Object>. Many examples on Stack Overflow shows how to cast from one data type to another but not from enum. I have tried doing it through stream but no luck. Here is my code

private enum Number{
  One, Two, Three;
}
final Map<Number, String> map = Collections.synchronizedMap(new EnumMap<Number, String> (Number.class));

populateMap(map);
Map<String, Object> newMap= new HashMap<String, Object>();

Now I want to do something like

newMap.putAll(map);

How can I do it through Stream APIs?

2

There are 2 best solutions below

1
gagan singh On
Map<String, Object> newMap = map.entrySet().stream()
        .collect(Collectors.toMap(e -> e.getKey().toString(),  Map.Entry::getValue));
1
Eric On

A more concise answer is,

final Map<Number, String> map = Collections.synchronizedMap(new EnumMap<>(Number.class));

Map<String, Object> newMap= new HashMap<>();

map.forEach((key, value) -> newMap.put(key.name(), value));