[英]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
的方法引用傳遞給Stream
的map
方法時,您試圖將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.