Java 将 Streams 与原始数据类型和相应的包装器一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23007422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Streams with primitives data types and corresponding wrappers
提问by ifloop
While playing around with Java8's Streams-API, I stumbled over the following:
在使用 Java8 的 Streams-API 时,我偶然发现了以下内容:
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).
要将原始包装器类对象的数组转换为Stream
我只需要调用Stream.of(array)
. 但是要转换原始数据类型的数组,我必须.of(array)
从相应的包装器(类)流类中调用(<-- 听起来很傻)。
An example:
一个例子:
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
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?
我的问题:这是为什么?这是否与例如它的行为Arrays.asList()
也仅适用于包装类数组有关?
采纳答案by Honza Zidek
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
.
爪哇8流框架有一个通用Stream<T>
的对象作为元素,以及三个原始流IntStream
,LongStream
,DoubleStream
对三个主要的原语。如果您使用原语,请在您的情况下使用后者之一IntStream
。
See the picture:
看图:
What lies behind is that:
背后的原因是:
Java genericscannot work with primitive types: it is possible to have only
List<Integer>
andStream<Integer>
, but notandList<int>
Stream<int>
When the Java Collectionsframework was introduced, it was introduced only for classes, so if you want to have a
List
ofint
s, you have to wrap them toInteger
s. This is costly!When the Java Streamsframework was introduced, they decided to get around this overhead and in parallelwith 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
.
Java 泛型不能与原始类型一起使用:可能只有
List<Integer>
andStream<Integer>
,但没有andList<int>
Stream<int>
当Java集合引入框架,据介绍只有上课,所以如果你想拥有
List
的int
S,你必须给他们换到Integer
秒。这是昂贵的!当Java Streams框架被引入时,他们决定绕过这个开销并与“面向类”的流并行(使用泛型机制),他们引入了三个额外的所有库函数集,专门为最重要的原始类型:
int
,long
,double
.
And see also a marvelous explanation here: https://stackoverflow.com/a/22919112/2886891
并在这里看到一个奇妙的解释:https: //stackoverflow.com/a/22919112/2886891