I need to know how I can apply a BiFunction
to two lists of different objects
List<A> listA;
List<B> listB;
private BiFunction<A,B,C> biFunction=new BiFunction<A,B,C>() {
@Override
public C apply(A a, B b) {
C c=new C();
return c;
}
};
I need to get a List<C>
and for that I have to use biFunction
with listA
and listB
.
I do not know how to do this in Java 8, the only way I know is this:
List<C> listC=new ArrayList<>();
for(int i=0;i<listA.size();i++)
listC.add(biFunction.apply(listA.get(i),listB.get(i)));
Obviously listA
and listB
have the same size.
It's a horrible solution, please can you suggest a better way?
As far as I know, the cleanliest way without using external libraries is this:
List<A> listA;
List<B> listB;
BiFunction<A, B, C> biFunction = (a, b) -> {
C c = new C();
return c;
};
List<C> listC = IntStream.range(0, listA.size())
.mapToObj(i -> biFunction.apply(listA.get(i), listB.get(i)))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With