Java 8: merge 2 string lists into the map

See English answers > clearest way to combine two lists into a map (Java)? 15

List<String> keys
List<String> values

I want to map these two lists to map < string, string > using java 8 streams The list has the same size and is sorted in the same way

I try to map these two in the following way

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

But it doesn't work at all – how can I do that? Thanks in advance:)

Solution

You can use the index of the intstream iteration list:

Map<String,String> result =
    IntStream.range(0,keys.size())
             .@R_784_2419@ed()
             .collect(Collectors.toMap(i -> keys.get(i),i -> values.get(i)));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>