Home > Back-end >  How to use Java Streams API to do element wise multiplication between 2 lists of same dimension
How to use Java Streams API to do element wise multiplication between 2 lists of same dimension

Time:08-10

I have 2 lists like:

List<Double> margins =  Arrays.asList(1.0,2.0,3.0,4.0,5.0);
List<Integer> quantity = Arrays.asList(1,2,3,4,5);

I want to do element wise multiplication between them, I know I can do it with standard for loop but I was wondering if we can achieve the same via the Stream API by making the process faster and less resource heavy.

Something like what python ML does with numpy arrays; instead of making a for loop they vectorize the thing which makes it faster.

CodePudding user response:

You can multiply the elements of your arrays with each other via stream, but it won't be more efficient than a traditional loop. However, for such small sets of data the overhead is so small it won't make any difference.

Here is an implementation via stream. Basically, you could use the IntStream class to iterate both of your lists from 0 to the size of the smallest list (excluded). Then, map each int index to a Double object representing the product of the i-th element of the margins list with the i-th element of the quantity list and finally collect the results into a List<Double>.

List<Double> margins = Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0);
List<Integer> quantity = Arrays.asList(1, 2, 3, 4, 5);

List<Double> res = IntStream.range(0, Math.min(margins.size(), quantity.size()))
        .mapToObj(i -> margins.get(i) * quantity.get(i))
        .collect(Collectors.toList());
  • Related