Java 8 for-loop mismatch: BinaryOperator vs List of Integer list

The following Java 8 code snippet assumes iteration over a list of binary (2-arg) operators / lambda functions. Eclipse generates an error The method o(int,int) is undefined for the type X. The error is related to the loop variable o. In case it matters, the Eclipse version is the Eclipse Java EE IDE for web developers, the Mars Release version (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 op type is changed to List, there is no compiler error.

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

Why does for-loop work for List<Integer>, but not for List<BinaryOperator<Integer>>, and how should I list lambda function lists in Java 8?

+4
source share
1 answer

BinaryOperator List , apply List:

public void f(List<BinaryOperator<Integer>> op) {
    for (BinaryOperator<Integer> o : op) {
        int x = o.apply(1,2);
    }
}
+7

Source: https://habr.com/ru/post/1611150/


All Articles