A common problem that i have when solving my programming homework is that i have two arrays and i want to combine them using a function
so that
.
For example if:
a = {1,2,3}
b = {3,4,5}
f = (i1, i2) -> i1 + i2
c should be
c = {4,6,8}
The best solution I could come up with is something like this:
public static <A,B,C> Iterator<C> merge(Iterable<A> a, Iterable<B> b, BiFunction<A,B,C> f){
Iterator<A> ai = a.iterator();
Iterator<B> bi = b.iterator();
return new Iterator<>() {
@Override
public boolean hasNext() {
return ai.hasNext() && bi.hasNext();
}
@Override
public C next() {
return f.apply(ai.next(), bi.next());
}
};
}
but because java handles generics the way it handles generics I would also have to create specialized versions for primitive arrays (e.g. double[]), which amplifies the problem that I don't want to copy and paste like 100 lines of code every time I start a new homework.
Is there a standard library way of doing this?
edit: double[] version
public static double[] merge(double[] a, double[] b, DoubleBinaryOperator f){
return IntStream.range(0, Math.min(a.length, b.length)).mapToDouble(i -> f.applyAsDouble(a[i], b[i])).toArray();
}