Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a map out of two arrays using streams in Java?

Say I have two arrays of Double

Double[] a = new Double[]{1.,2.,3.};
Double[] b = new Double[]{10.,20.,30.};

Using Java streams, how do I create a map (Map<Double,Double> myCombinedMap;) that combines the two arrays for example in the following way:

System.out.println(myCombinedMap);
{1.0=10.0, 2.0=20.0, 3.0=30.0}

I guess am looking for something similar to Python zip with Java streams, or an elegant workaround.

I think this question differs from this one (pointed out as possible duplicate) because is centered on Java8 streams, which were not yet available at the time the possible duplicate question was asked.

like image 907
JacoSolari Avatar asked Sep 13 '19 10:09

JacoSolari


1 Answers

use IntStream and collect to a map:

IntStream.range(0, a.length)
         .boxed()
         .collect(toMap(i -> a[i], i -> b[i]));
like image 146
Ousmane D. Avatar answered Sep 28 '22 10:09

Ousmane D.