Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 streams transformations and List

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

like image 211
AntonBoarf Avatar asked Jan 27 '23 05:01

AntonBoarf


2 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()))
               );
like image 180
davidxxx Avatar answered Mar 13 '23 00:03

davidxxx


 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()));
 });
like image 32
Eugene Avatar answered Mar 13 '23 01:03

Eugene