考虑这个转换示例(请参阅关于应该发生什么的详细描述 here ):
Map<String, Integer> transform(Map<Integer, List<String>> old) {
old.entrySet().stream()
.flatMap(entry -> entry.getValue().stream()
.map(letter -> letter.toLowerCase())
.map(lowerCaseLetter -> new SimpleEntry<String, Integer>(lowerCaseLetter, entry.getKey())))
// at this point, the type is Stream<Object>, not Stream<SimpleEntry<String,Integer>>
.collect(Collectors.toMap());
}
为什么有关特定类型的信息在这里丢失,我该如何解决?
最佳答案
Eclipse 在其自身的编译器(尤其是类型推断)和 Java 8 功能方面仍然存在问题。在这种情况下,当您遇到此类问题时,请先尝试使用 javac 进行编译。如果确实编译成功,那么肯定是 Eclipse 问题。
如果你需要坚持使用 Eclipse,你也许可以通过提供类型参数来帮助 ECJ(Eclipse 的编译器),但通常你不应该这样做(在早期版本中可能是这样,但 java 编译器已经对类型推断)。
您可以向 Eclipse 开发团队提交错误(在您拥有最新版本之前检查),但 Java 8 的错误跟踪器非常密集。
一种替代方法是切换到使用 javac 的 IntelliJ,这是我在 Java 8 之后切换到它的主要原因之一......
查看您的代码,您可以将其缩短一些:
Map<String, Integer> transform(Map<Integer, List<String>> old) {
return old.entrySet().stream()
.flatMap(e -> e.getValue().stream().map(s -> new SimpleEntry<>(s.toLowerCase(), e.getKey())))
.collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));
}
关于Java 8 功能 : Lost type information in the middle of the way,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29793714/