将Streams与原语数据类型和相应的包装器一起使用 [英] Using Streams with primitives data types and corresponding wrappers
问题描述
在玩Java8的Streams-API时,我偶然发现了以下内容:
While playing around with Java8's Streams-API, I stumbled over the following:
将原始包装器classe对象数组转换为 Stream
我只需要调用 Stream.of(array)
。但是要转换原始数据类型的数组,我必须从相应的包装器(类)流类调用 .of(array)
(< - 听起来很傻) 。
To convert an array of primitive wrapper classe objects into a Stream
I just have to call Stream.of(array)
. But to convert an array of primitive data types, I have to call .of(array)
from the corresponding wrapper (class) stream class (<-- that sounds silly).
一个例子:
final Integer[] integers = {1, 2, 3};
final int[] ints = {1, 2, 3};
Stream.of(integers).forEach(System.out::println); //That works just fine
Stream.of(ints).forEach(System.out::println); //That doesn't
IntStream.of(ints).forEach(System.out::println); //Have to use IntStream instead
我的问题(s ):
这是为什么?这与例如 Arrays.asList()
的行为也适用于包装类数组?
My question(s):
Why is this? Does this correlate to e.g. the behaviour of Arrays.asList()
which also just works for wrapper class arrays?
推荐答案
Java 8流框架具有通用的 Stream< T>
作为元素的对象,以及三个基本流 IntStream $ c $主要三个基元的c>,
LongStream
, DoubleStream
。如果您使用原语,请使用后者之一,在您的情况下 IntStream
。
Java 8 stream framework has a generic Stream<T>
for objects as elements, and three primitive streams IntStream
, LongStream
, DoubleStream
for the main three primitives. If you work with primitives, use one of those latter, in your case IntStream
.
查看图片:
背后的原因是:
-
Java泛型不能与原始类型一起使用:可能只有
List< Integer>
和Stream< Integer>
,但不是List< int>
Stream< int>
Java generics cannot work with primitive types: it is possible to have only
List<Integer>
andStream<Integer>
, but notandList<int>
Stream<int>
当 Java Collections 框架,它仅针对类引入,所以如果你想要一个列表
int
s,你必须将它们包装到整数
秒。这很昂贵!
When the Java Collections framework was introduced, it was introduced only for classes, so if you want to have a List
of int
s, you have to wrap them to Integer
s. This is costly!
当 Java Streams 框架,他们决定绕过这个开销和并行与面向类的流(使用泛型机制),他们介绍了三个所有库函数的额外集合,专为最重要的原始类型设计: int
, long
, double
。
When the Java Streams framework was introduced, they decided to get around this overhead and in parallel with the "class-oriented" streams (using the generics mechanism), they introduced three extra sets of all the library functions, specifically designed for the most important primitive types: int
, long
, double
.
此处还可以看到一个奇妙的解释: https://stackoverflow.com/a/22919112/2886891
And see also a marvelous explanation here: https://stackoverflow.com/a/22919112/2886891
这篇关于将Streams与原语数据类型和相应的包装器一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!