为什么我们必须将Collectors.toList()返回的List转换为List< Integer>即使Stream的元素已经映射到Integer? [英] 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?

查看:505
本文介绍了为什么我们必须将Collectors.toList()返回的List转换为List< Integer>即使Stream的元素已经映射到Integer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将原始 Stream 映射到 Stream< Integer> ,然后将元素收集到列表与LT;整数>

I'm mapping a raw Stream to a Stream<Integer> and then collect the elements to a List<Integer>.

为什么我必须将 collect(Collectors.toList())的结果转换为 List< Integer> 如果我的mapper - .map(str - >((String)str)。length()) - 已经映射到整数

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?

我的代码:

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


推荐答案

调用 list.stream(原始列表上的生成原始。在 Stream 上调用 map 不会更改 Stream 到通用的 Stream< Integer> 。它将其更改为另一个原始 Stream 。因此,当您调用 collect(Collectors.toList())时,您将获得原始列表并且必须将其强制转换为(List< Integer>)

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.

这篇关于为什么我们必须将Collectors.toList()返回的List转换为List&lt; Integer&gt;即使Stream的元素已经映射到Integer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆