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?
Map<String, Object> newMap = map.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue));
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.