我尝试在Collectors.toMap
Stream
上使用java8的ZipEntry
。它可能不是最好的主意,因为在处理过程中可能会出现异常,但我想它应该是可能的。
我现在收到一个编译错误(类型推理引擎,我猜),我不明白。
以下是一些提取的演示代码:
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
的流,那么{<1}}
作为参考,这是构建错误的开始,它非常模糊:
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...
答案 0 :(得分:7)
问题似乎是由于流类型使用外卡 - 不确定这是否是预期的行为。解决方法是:
zipFile.stream().map(ZipEntry.class::cast) //or .map(z -> (ZipEntry) z)