[英]java8 Collectors.toMap() limitation?
我試圖在ZipEntry
Stream
上使用java8的Collectors.toMap
。 它可能不是最好的主意,因為在處理過程中可能會出現異常,但我想它應該是可能的。
我現在得到一個編譯錯誤(類型推理引擎,我猜),我不明白。
這是一些提取的演示代碼:
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class TestMapCollector {
private static class MyObject {
}
public static void main(String[] argv) throws IOException {
try (ZipFile zipFile = new ZipFile("test")) {
Map<String, MyObject> result = zipFile.stream()
.map(ZipEntry::getName)
.collect(Collectors.toMap(f -> "test", f -> new MyObject()));
}
}
}
此代碼按原樣構建,但如果您只注釋.map(ZipEntry::getName)
行,則不構建代碼。 好像toMap
收集器可以工作,如果輸入是一個String
流,但如果輸入是ZipEntry
流?
作為參考,這是構建錯誤的開始,它非常模糊:
no suitable method found for collect(Collector<Object,CAP#1,Map<String,MyObject>>)
method Stream.<R#1>collect(Supplier<R#1>,BiConsumer<R#1,? super CAP#2>,BiConsumer<R#1,R#1>) is not applicable
(cannot infer type-variable(s) R#1
(actual and formal argument lists differ in length))
method Stream.<R#2,A>collect(Collector<? super CAP#2,A,R#2>) is not applicable
(cannot infer type-variable(s) R#2,A,CAP#3,T#2,K,U
(argument mismatch; Collector<CAP#2,CAP#4,Map<Object,Object>> cannot be converted to Collector<? super CAP#2,CAP#4,Map<Object,Object>>))
where R#1,T#1,R#2,A,T#2,K,U are type-variables:
R#1 extends Object declared in method <R#1>collect(Supplier<R#1>,BiConsumer<R#1,? super T#1>,BiConsumer<R#1,R#1>)
T#1 extends Object declared in interface Stream
R#2 extends Object declared in method <R#2,A>collect(Collector<? super T#1,A,R#2>)
A extends Object declared in method <R#2,A>collect(Collector<? super T#1,A,R#2>)
T#2 extends Object declared in method <T#2,K,U>toMap(Function<? super T#2,? extends K>,Function<? super T#2,? extends U>)
K extends Object declared in method <T#2,K,U>toMap(Function<? super T#2,? extends K>,Function<? super T#2,? extends U>)
U extends Object declared in method <T#2,K,U>toMap(Function<? super T#2,? extends K>,Function<? super T#2,? extends U...
問題似乎是由於流類型使用外卡 - 不確定這是否是預期的行為。 解決方法是:
zipFile.stream().map(ZipEntry.class::cast) //or .map(z -> (ZipEntry) z)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.