简体   繁体   English

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

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

I have the following code: 我有以下代码:

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());

}

I get the following error: 我收到以下错误:

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>)

I am new to streams, and reading the docs doesn't clear this up for me. 我是流媒体的新手,阅读文档并不能为我解决这个问题。 Any help will be appreciated. 任何帮助将不胜感激。

getValue is a method that takes no arguments. getValue是不带参数的方法。 When you try to pass a method reference of getValue to Stream 's map method, you are trying to pass the Stream 's element to getValue , but getValue doesn't take any arguments. 当您尝试将getValue的方法引用传递给Streammap方法时,您试图将Stream的元素传递给getValue ,但是getValue不接受任何参数。

You can replace the method reference with a lambda expression if you wish to ignore the outer element of the Stream: 如果您希望忽略Stream的outer元素,则可以用lambda表达式替换方法引用:

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

However, this will lead to a NullPointerException , since you don't initialize public static inner i1 anywhere, so invoking the outer constructor will throw that exception. 但是,这将导致NullPointerException ,因为您没有在任何地方初始化public static inner i1 ,因此调用outer构造函数将引发该异常。

It's hard to suggest how to fix that without knowing what you are trying to do. 在不知道您要做什么的情况下很难提出解决方案。

I don't know if it makes sense to have a static member of type inner in your outer class, but if it makes sense, you should probably initialize it in a static initializer block (or in its declaration). 我不知道在您的outer类中拥有一个类型为inner的静态成员是否有意义,但是如果有意义,您可能应该在静态初始化程序块(或其声明)中对其进行初始化。

You could, for example, change 例如,您可以更改

public static inner i1;

to

public static inner i1 = new inner();

which will eliminate the exception. 这将消除异常。

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

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