Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2 collections into a Map

I have 2 Lists as List<String> a and List<String> b of equal size.

What is the most efficient way to create a Map<String, String> in Java 8 using lambdas or something else where List<String> a are the keys and List<String> b are the values?

The Java 7 way is as follows:

Map<String, String> map = new HashMap<String, String>();
for(int i=0;i<a.size();i++)
    map.put(a.get(i), b.get(i));
like image 699
Pankaj Singhal Avatar asked Nov 16 '25 05:11

Pankaj Singhal


1 Answers

Since there is no zip operation on Stream (and no Pair class), a simple solution is to use an IntStream and loop over the indexes of each List.

Map<String, String> map =
    IntStream.range(0, a.size()).boxed().collect(Collectors.toMap(a::get, b::get));

Alternatively, you can use the StreamEx library which offers a zip method and have:

Map<String, String> map = EntryStream.zip(a, b).toMap();
like image 83
Tunaki Avatar answered Nov 18 '25 20:11

Tunaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!