无法从java.lang.Integer转换为R
我有以下代码:无法从java.lang.Integer转换为R,java,java-8,java-stream,Java,Java 8,Java Stream,我有以下代码: 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);
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;
公共整数getValue(){
返回i;
}
公共void setValue(整数i){
这个。i=i;
}
}
类外部{
公共静态内部i1;
外部(整数i){
i1.设定值(i);
}
}
公共类MyClass{
公共图书馆{
List 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>)
required:FunctiongetValue
是一个不带参数的方法。
当您尝试将getValue
的方法引用传递给Stream
的map
方法时,您尝试将Stream
的元素传递给getValue
,但getValue
不接受任何参数
如果希望忽略流的outer
元素,可以使用lambda表达式替换方法引用:
List<Integer> ll = Arrays.asList(new outer(2)).stream().map(o -> outer.i1.getValue()).collect(Collectors.toList());
到
这将消除异常。getValue
是一种不带参数的方法。
当您尝试将getValue
的方法引用传递给Stream
的map
方法时,您尝试将Stream
的元素传递给getValue
,但getValue
不接受任何参数
如果希望忽略流的outer
元素,可以使用lambda表达式替换方法引用:
List<Integer> ll = Arrays.asList(new outer(2)).stream().map(o -> outer.i1.getValue()).collect(Collectors.toList());
到
这将消除异常。您的代码非常奇怪。为什么您要使用构造函数修改静态值?为什么您要尝试将外部
的实例映射到内部
的静态实例?您希望它产生什么?@shmosel这只是我编写的一个测试代码,以了解流API的工作情况。您的代码e很奇怪。为什么你要用构造函数修改静态值?为什么你要尝试将外部
的实例映射到内部
的静态实例?你希望它产生什么?@shmosel这只是我编写的一个测试代码,目的是了解流API的工作情况。我想我明白了。传递给map的方法引用是ap如果对象适用于流的对象类型,则将其应用于对象。但是,还有一种情况是,您可以传递将流对象作为参数的方法引用。我在这里已经解释过:我想我知道了。如果对象适用于流的对象类型,则将传递给map的方法引用应用于对象。B但是,还有一种情况,您可以传递将流对象作为参数的方法引用。我在这里已经解释过了:
public static inner i1 = new inner();