major
major

Reputation: 57

Convert Map<String, List<Object>> to Map<String, List<String>> in java 1.8

I have a Map<String, List<Object>> , I would like to convert it to Map<String, List<String>> in java 8 .

In Java 1.7 I was using a function to extract value from Map and then wrote another method declared empty List , used for loop to extract each element and then added to List Object in java 1.7

Any suggestions to do same in java 8 using lambda expressions

Thanks in advance

Upvotes: 0

Views: 205

Answers (1)

Kartik
Kartik

Reputation: 7917

You can use this:

Map<String, List<String>> result = map.entrySet().stream()
        .map(e -> Map.entry(e.getKey(),
                e.getValue().stream()
                        .map(o -> (String) o) //or Object::toString depending on the object
                        .collect(Collectors.toList())))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Map.entry is from Java 9, you can use AbstractMap.SimpleEntry if you are on Java 8.

Upvotes: 1

Related Questions