【问题标题】:Java 8 for-loop inconsistency: List of BinaryOperator vs List of IntegerJava 8 for 循环不一致:BinaryOperator 列表与整数列表
【发布时间】:2016-01-08 20:12:13
【问题描述】:

在下面的 Java 8 代码 sn-p 中,目的是遍历二进制 (2-arg) 运算符/lambda 函数的列表。 Eclipse 生成错误The method o(int,int) is undefined for the type X。该错误与循环变量o 相关联。如果相关,Eclipse 的版本是“面向 Web 开发人员的 Eclipse Java EE IDE”,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);
        }
    }
}

但是,如果将op的类型改为List,则不会出现编译错误。

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

为什么 for 循环适用于 List&lt;Integer&gt; 而不适用于 List&lt;BinaryOperator&lt;Integer&gt;&gt;,以及如何在 Java 8 中迭代 lambda 函数列表?

【问题讨论】:

  • 只是一个注释(与您的问题不严格相关):在 Java 8 中,要对数据集合进行操作(并使用 labda),您使用集合框架而不是流框架?我认为这篇文章对你很有用:oracle.com/technetwork/articles/java/…
  • @PierpaoloCira 谢谢 - 该文档看起来非常全面。我熟悉流和集合框架,但是在将纯 lambda 函数调用与 Java 方法调用混合时犯了一个新手错误。

标签: java list for-loop lambda java-8


【解决方案1】:

如果您希望在循环中应用您的ListBinaryOperators,您必须为List 的每个元素调用该接口的apply 方法:

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

【讨论】:

  • 感谢 Eran - 这是我的新手错误。
猜你喜欢
  • 1970-01-01
  • 2017-07-08
  • 2015-05-08
  • 1970-01-01
  • 2011-12-08
  • 2017-11-17
  • 1970-01-01
  • 2017-03-19
  • 2020-05-19
相关资源
最近更新 更多