Java 8 streams transformations and List

Viewed 106

I have a :

Map<String,List<String>> persons

And each String element in the List<String> represents a Long

So I want to turn my Map<String,List<String>> into a Map<String,List<Long>>

The problem is my List are encapsulated into a map. I know with a single List, I can do that :

list.stream().map(s -> Long.valueOf(s)).collect(Collectors.toList());

But my case is a bit different. Any idea how to proceed ?

Thanks

3 Answers

You could use this collect :

list.stream().map(s -> Long.valueOf(s)).collect(Collectors.toList());

as the valueMapper parameter of toMap() applied on the stream of the map.

Which would give :

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;

Map<String,List<String>> persons = ...;
Map<String,List<Long>> personsMapped = 
persons.entrySet()
       .stream()
       .collect(toMap(Entry::getKey, e -> e.getValue().stream()
                                                      .map(Long::valueOf)
                                                      .collect(toList()))
               );
 Map<String,List<String>> persons = ...

 Map<String, List<Long>> result = new HashMap<>();

 persons.forEach((key, value) -> {
        result.put(key, value.stream().map(Long::valueOf).collect(Collectors.toList()));
 });

You may do it like so,

Map<String, List<Long>> longMap = persons.entrySet().stream()
    .collect(Collectors.toMap(Map.Entry::getKey,
        e -> e.getValue().stream().map(s -> Long.valueOf(s)).collect(Collectors.toList())));
Related