An elegant way to combine two arrays in Java 8

I like to combine two common arrays in pairs on BiFunction . Here you see a naive implementation:

 <A,B,C> C[] combine(A[] as, B[] bs, BiFunction<A,B,C> op) { if (as.length == bs.length) { C[] cs = (C[]) new Object[as.length]; for(int i = 0; i < as.length; i++) { cs[i] = op.apply(as[i], bs[i]); } return cs; } else { throw new IllegalArgumentException(); } } 

I wonder if there is a more elegant way to do this without a for loop - perhaps with Java 8 Stream . I would appreciate your suggestions.

+5
source share
2 answers

You can use the Arrays.setAll method:

 C[] cs = (C[]) new Object[as.length]; Arrays.setAll(cs, i -> op.apply(as[i], bs[i])); 

Or, if op very expensive to compute, you can also use Arrays.parallelSetAll .

+5
source

you can use IntStream.range to generate indexes and then work with them.

 C[] cs = (C[])IntStream.range(0, as.length) .mapToObj(i -> op.apply(as[i], bs[i])) .toArray(); 
+3
source

Source: https://habr.com/ru/post/1274287/


All Articles