I am trying to convert a Map to another Map where the new key is simply the original key toString(). With the streams API I do this as follows:
mapMap.entrySet().stream().collect(Collectors.toMap(
(Map.Entry entry) -> entry.getKey().toString(),
(Map.Entry entry) -> entry.getValue()
));
The problem is that this doesn't preserve the internal Map type. I don't mind returning a TreeMap if the original map happens to be a HashMap, but the other way around is a problematic as sorting of the elements is removed. I've been fooling around with variations of the above code to get this done, but I don't seem to get very far. Right now, I have written it without streams, as follows:
TreeMap<String, Integer> stringMap = new TreeMap<>();
for (OriginalType t: originalMap.keySet()) {
stringMap.put(t.toString(), originalMap.get(t));
}
Can anyone put me in the right direction to do this with streams? Thanks
There is an overload of Collectors.toMap which will allow you to specify which type of map you want returned.
mapMap.entrySet().stream().collect(Collectors.toMap(
(Map.Entry entry) -> entry.getKey().toString(),
(Map.Entry entry) -> entry.getValue(),
(val1, val2) -> { throw new RuntimeException("Not expecting duplicate keys"); },
() -> new TreeMap<>()
));
(A note about the third argument: it is intended as a function which will merge two values together that have the same key. When I don't expect these things to happen, I prefer to throw an exception.)
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