Why do we have to cast the List returned by Collectors.toList() to List<Integer> even though the elements of the Stream are already mapped to Integer? [duplicate]

左心房为你撑大大i 提交于 2020-01-01 19:35:08

问题


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());

回答1:


Calling list.stream() on a raw List produces a raw Stream. calling map on that Stream doesn't change that Stream to a generic Stream<Integer>. It changes it to another raw Stream. Therefore when you call collect(Collectors.toList()), you get a raw List and have to cast it to (List<Integer>).

Conclusion : don't use raw types.



来源:https://stackoverflow.com/questions/45054145/why-do-we-have-to-cast-the-list-returned-by-collectors-tolist-to-listinteger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!