Using Streams / Collecting to Transform a Map

I am trying to convert a map to another map where the new key is just the original toString () key. With the streams API, I do it like this:

    mapMap.entrySet().stream().collect(Collectors.toMap(
            (Map.Entry entry) -> entry.getKey().toString(),
            (Map.Entry entry) -> entry.getValue()
    ));

      

The problem is that this does not preserve the internal type of the card. I don't mind returning a TreeMap if the original map is a HashMap, but the other way around is a problem since the sorting of the items is removed. I have cheated with variations of the above code to do this, but I don't seem to go very far. Right now, I wrote it without threads, like this:

    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 to

+3


source to share


1 answer


There is an overload Collectors.toMap

that will allow you to specify what type of card you want to return.

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 on the third argument: it is intended as a function that concatenates two values ​​together with the same key. When I don't expect this to happen, I prefer the exception.)

+5


source







All Articles