Reputation: 2558
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)
Upvotes: 7
Views: 4215
Reputation: 34460
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));
Upvotes: 2
Reputation: 7504
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);
}
);
Upvotes: 2
Reputation: 375
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
Upvotes: 2
Reputation: 311163
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()));
Upvotes: 9