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));
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With