Arrays.stream(array)vs Arrays.asList(array).stream() [英] Arrays.stream(array) vs Arrays.asList(array).stream()

查看:497
本文介绍了Arrays.stream(array)vs Arrays.asList(array).stream()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题中,已经回答过两个表达式都相等,但在这种情况下,它们会产生不同的结果。对于给定的 int []得分,为什么这样做:

In this question it has already been answered that both expressions are equal, but in this case they produce different results. For a given int[] scores, why does this work:

Arrays.stream(scores)
        .forEach(System.out::println);

...但这不是:

Arrays.asList(scores).stream()
        .forEach(System.out::println);

据我所知 .stream()可以在任何Collection上调用,列表肯定是。第二个代码片段只返回一个包含整个数组而不是元素的流。

As far as I know .stream() can be called on any Collection, which Lists definitely are. The second code snippet just returns a stream containing the array as a whole instead of the elements.

推荐答案

你看到的行为不是特定于 Stream s。
Arrays.asList(得分)在传递给它时返回 List< int []> 一个 int [] ,因为泛型类型参数不能被基本类型替换。因此,当您调用 asList(T ... a)时,编译器使用 int [] 代替 T

The behavior you see is not specific to Streams. Arrays.asList(scores) returns a List<int[]> when you pass to it an int[], since a generic type parameter can't be replaced by a primitive type. Therefore, when you call asList(T... a), the compiler uses int[] in place of T.

如果您将得分更改为整数[] ,你会得到你期望的输出(即 Arrays.asList(得分)将返回列表<整数> ) 。

If you change scores to Integer[], you'll get the output you expect (i.e. Arrays.asList(scores) will return a List<Integer>).

这篇关于Arrays.stream(array)vs Arrays.asList(array).stream()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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