Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using streams/collect to transform a Map

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

like image 623
Yves V. Avatar asked Dec 06 '25 05:12

Yves V.


1 Answers

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.)

like image 59
Joe C Avatar answered Dec 08 '25 22:12

Joe C