4

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?

Helder Pereira
  • 5,522
  • 2
  • 35
  • 52
dommy1985
  • 73
  • 1
  • 6

2 Answers2

8

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());
Helder Pereira
  • 5,522
  • 2
  • 35
  • 52
1

Using StreamUtils from protonpack:

Stream<C> streamC = StreamUtils.zip(listA, listB, biFunction);

It is open source so don't hesitate to give it a look.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • 1
    `StreamUtils.zip` does not zip lists, it zips streams, so you should use it like `StreamUtils.zip(listA.stream(), listB.stream(), biFunction)`. Also it should be noted that unlike @HelderPereira solution this version is not parallel-friendly. – Tagir Valeev Aug 18 '15 at 02:18