无法从java.lang.Integer转换为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 ll = Arrays.asList(new outer(2)).stream().map(outer.i1::getValue).collect(Collectors.toList()); } 

我收到以下错误:

 required: Function 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 map(Function) 

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

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

如果要忽略Stream的outer元素,可以使用lambda表达式替换方法引用:

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

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

很难在不知道你想要做什么的情况下建议如何解决这个问题。

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

例如,你可以改变

 public static inner i1; 

 public static inner i1 = new inner(); 

这将消除例外。