This question already has an answer here:
- What is a raw type and why shouldn't we use it? 15 answers
- Why does the Streams API need a hint for generic type in this case? 1 answer
- Why does javac complain about generics unrelated to the class' type arguments? [duplicate] 1 answer
I'm mapping a raw Stream
to a Stream<Integer>
and then collect the elements to a List<Integer>
.
Why do I have to cast the result of collect(Collectors.toList())
to List<Integer>
if my mapper - .map(str -> ((String)str).length())
- already maps to Integer
?
My code:
List list = Arrays.asList("test", "test2");
List<Integer> lengths = (List<Integer>) list.stream()
.map(str -> ((String)str).length())
.collect(Collectors.toList());
If I don't use a raw List
, there's no need to cast:
List<String> list = Arrays.asList("test", "test2");
List<Integer> lengths = list.stream()
.map(str -> str.length())
.collect(Collectors.toList());