我有以下代码:
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
的方法引用传递给 Stream
的 map
方法时,您正在尝试传递 Stream
code> 的元素传递给 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 inside i1
,因此调用 outer
构造函数将抛出该异常。
在不知道你想要做什么的情况下,很难建议如何解决这个问题。
我不知道在 outer
类中拥有 inner
类型的静态成员是否有意义,但如果有意义,您可能应该初始化它在静态初始化 block 中(或其声明中)。
例如,您可以更改
public static inner i1;
至
public static inner i1 = new inner();
这将消除异常。
关于java - 无法从 java.lang.Integer 转换为 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41531275/