Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Apply a BiFunction to two lists of different objects [duplicate]

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?

like image 865
dommy1985 Avatar asked Jan 07 '23 18:01

dommy1985


1 Answers

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());
like image 144
Helder Pereira Avatar answered Jan 19 '23 19:01

Helder Pereira