Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Merge 2 String Lists into Map [duplicate]

I have the following:

List<String> keys
List<String> values

I would like map these two lists to a Map<String, String> using Java 8 Streams. The lists have both the same size and are sorted the same way.

I tried to map these two with the following

Map<String, String> result= keys.stream().
        collect(Collectors.toMap(keys::get, values::get));

But this doesnt work at all - how can I do this correclty? Thanks in advance :)

like image 955
Remo Avatar asked Oct 22 '17 12:10

Remo


1 Answers

You can iterate over the indices of the Lists with an IntStream:

Map<String, String> result =
    IntStream.range(0,keys.size())
             .boxed()
             .collect(Collectors.toMap(i -> keys.get(i), i -> values.get(i)));
like image 105
Eran Avatar answered Nov 03 '22 08:11

Eran