Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 for-loop inconsistency: List of BinaryOperator vs List of Integer

In the following Java 8 code snippet, the intention is to iterate through a list of binary (2-arg) operators / lambda functions. Eclipse generates the error The method o(int,int) is undefined for the type X. The error is associated with the loop variable o. In case it is relevant, the version of Eclipse is "Eclipse Java EE IDE for Web Developers", Mars Release (4.5.0).

import java.util.List;
import java.util.function.BinaryOperator;
public class X {
    public void f(List<BinaryOperator<Integer>> op) {
        for (BinaryOperator<Integer> o : op) {
            int x = o(1,2);
        }
    }
}

However, if the type of op is changed to List, there is no compiler error.

public void f(List<Integer> op) {
    for (Integer o : op) {
        int x = o;
    }
}

Why does the for-loop work for List<Integer> but not for List<BinaryOperator<Integer>>, and how should lists of lambda functions be iterated in Java 8?

like image 791
Lawrence Avatar asked Mar 14 '23 12:03

Lawrence


1 Answers

If you wish to apply the BinaryOperators of your List in a loop, you must invoke the apply method of that interface for each element of the List :

public void f(List<BinaryOperator<Integer>> op) {
    for (BinaryOperator<Integer> o : op) {
        int x = o.apply(1,2);
    }
}
like image 172
Eran Avatar answered Mar 23 '23 01:03

Eran