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

JacoSolari :

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.

Ousmane D. :

use IntStream and collect to a map:

IntStream.range(0, a.length)
         .boxed()
         .collect(toMap(i -> a[i], i -> b[i]));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=163735&siteId=1