Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: change type of entries return Map

I got the follwoing question: I have a Map<?,?> and I parse it from an PList file, simplified like:

Map<String, String> m  = (Map<String, String>) getMap();

The getMap() method just reads the file (.plist). I want to parse all the values to String, but unfortunately the Map contains Integers, causing an error later in the process. So I wanted to write a method using the filter to convert everything to String:

My approach is:

m.entrySet().stream()
    .map(e -> e.getValue())
    .filter(e -> e instanceof Integer)
    .map(e -> String.valueOf(e))
    .collect(Collectors.toMap(e -> e.keys(), e -> e.getValue()));

The problem is, that the collect at the end is not working, how can I fix this? The result should be a map again.

Thank you a lot!

like image 902
Tobias Schäfer Avatar asked Dec 14 '22 18:12

Tobias Schäfer


1 Answers

You're misunderstanding how Collectors.toMap works - it takes two functions, one that given an entry produces a new key, and one that given an entry produce a new value. Each entry in the map then has both of these functions applied to it and the resulting key/value for that single element are used to construct the new entry in the new map.

Also, by mapping each entry to just the value, you lose the association between keys and values, which means you can't reconstruct the map correctly.

A corrected version would be:

Map<String, String> n;
n = m.entrySet()
     .stream()
     .filter(e -> e.getValue() instanceof Integer)
     .collect(Collectors.toMap(e -> e.getKey(),
                               e -> String.valueOf(e.getValue())));
like image 195
hnefatl Avatar answered Dec 18 '22 00:12

hnefatl