I have the following map:
Map<DataFields, String> myMap;
But I need to convert it to the following:
Map<String, String> myMap;
My best feeble attempt which doesn't even compile is:
myMap.keySet().stream().map(k -> k.name()).collect(Collectors.toMap(k, v)
You need to stream the entrySet()
(so you have both the keys and the values), and collect them to a map:
Map<String, String> result =
myMap.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey().name(), e -> e.getValue()));
Map<String, String> result = myMap
.entrySet() // iterate over all entries (object with tow fields: key and value)
.stream() // create a stream
.collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue()));
// collect to map: convert enum Key value toString() and copy entry value
Another way of doing same without Collectors helper. Using entryset
will make it very easy to map.
map.entrySet()
.stream()
.collect(
() -> new HashMap<String, String>(),
(Map newMap, Map.Entry<DataFields, String> entry) -> {
newMap.put(entry.getKey().name(), entry.getValue());
}
,
(Map map1, Map map2) -> {
map.putAll(map2);
}
);
A Java 8, succint way to do it (without streams):
Map<String, String> result = new HashMap<>();
myMap.forEach((k, v) -> result.put(k.name(), v));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With