2

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?

1
  • 1
    What data should result map hold? I am guessing that String should be name of enum, but what should be held under Object value? Commented Jun 26, 2018 at 14:35

2 Answers 2

2

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

1 Comment

Perfect. Thank You :)
2
Map<String, Object> newMap = map.entrySet().stream()
        .collect(Collectors.toMap(e -> e.getKey().toString(),  Map.Entry::getValue));

1 Comment

Works like a charm. Thank you :)

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.