繁体   English   中英

无法从java.lang.Integer转换为R

[英]Cannot convert from java.lang.Integer to R

我有以下代码:

class inner {
    Integer i;
    public Integer getValue() {
        return i;
    }
    public void setValue(Integer i) {
        this.i = i;
    }
}

class outer {
    public static inner i1;

    outer(Integer i) {
        i1.setValue(i);
    }
}

public class MyClass{
public void main() {
    List<Integer> ll = Arrays.asList(new outer(2)).stream().map(outer.i1::getValue).collect(Collectors.toList());

}

我收到以下错误:

required: Function<? super Object,? extends R>
  found: outer.i1::getValue
  reason: cannot infer type-variable(s) R
    (argument mismatch; invalid method reference
      method getValue in class inner cannot be applied to given types
        required: no arguments
        found: Object
        reason: actual and formal argument lists differ in length)
  where R,T are type-variables:
    R extends Object declared in method <R>map(Function<? super T,? extends R>)

我是流媒体的新手,阅读文档并不能为我解决这个问题。 任何帮助将不胜感激。

getValue是不带参数的方法。 当您尝试将getValue的方法引用传递给Streammap方法时,您试图将Stream的元素传递给getValue ,但是getValue不接受任何参数。

如果您希望忽略Stream的outer元素,则可以用lambda表达式替换方法引用:

List<Integer> ll = Arrays.asList(new outer(2)).stream().map(o -> outer.i1.getValue()).collect(Collectors.toList());

但是,这将导致NullPointerException ,因为您没有在任何地方初始化public static inner i1 ,因此调用outer构造函数将引发该异常。

在不知道您要做什么的情况下很难提出解决方案。

我不知道在您的outer类中拥有一个类型为inner的静态成员是否有意义,但是如果有意义,您可能应该在静态初始化程序块(或其声明)中对其进行初始化。

例如,您可以更改

public static inner i1;

public static inner i1 = new inner();

这将消除异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM