Consider this transform example (see detailed description about what should happen 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());
}
Why is the information about the specific type lost here and how can I fix this?
Eclipse still have troubles with its own compiler (especially on type inference) and the Java 8 features. In this case when you're facing this kind of issue, try to compile with javac first. If it does compile then it's certainly an Eclipse problem.
If you need to stick with Eclipse you can maybe help ECJ (Eclipse's compiler) by providing the type parameter, but normally you shouldn't do it (it may be true in earlier versions but the java compiler has made huge improvements on type inference).
You can fill a bug to the Eclipse dev's team (check before that you have the last version), but the bug-tracker for java 8 is very dense.
One alternative would be to switch to IntelliJ which uses javac, and this is one of the main reason I switched to it after Java 8...
Looking at your code, you can make it slightly shorter:
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));
}
You are not right. Type information is preserved. At least in:
java version "1.8.0_40" Java(TM) SE Runtime Environment (build 1.8.0_40-b25) Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With