如何将 Java 8 IntStream 转换为列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23674624/
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
How do I convert a Java 8 IntStream to a List?
提问by Eric Wilson
I'm looking at the docs for the IntStream
, and I see an toArray
method, but no way to go directly to a List<Integer>
我正在查看 的文档IntStream
,我看到了一种toArray
方法,但无法直接转到List<Integer>
Surely there is a way to convert a Stream
to a List
?
当然有一种方法可以将 a 转换Stream
为 aList
吗?
采纳答案by Ian Roberts
IntStream::boxed
IntStream::boxed
IntStream::boxed
turns an IntStream
into a Stream<Integer>
, which you can then collect
into a List
:
IntStream::boxed
将 anIntStream
变成 a Stream<Integer>
,然后您可以将其collect
变成 a List
:
theIntStream.boxed().collect(Collectors.toList())
The boxed
method converts the int
primitive values of an IntStream
into a stream of Integer
objects. The word "boxing"names the int
? Integer
conversion process. See Oracle Tutorial.
该boxed
方法将 a 的int
原始值转换IntStream
为Integer
对象流。“拳击”这个词命名为int
?Integer
转换过程。请参阅Oracle 教程。
回答by Nikhil Nanivadekar
You can use primitive collections available in Eclipse Collectionsand avoid boxing.
您可以使用Eclipse Collections 中提供的原始集合并避免装箱。
MutableIntList list =
IntStream.range(1, 5)
.collect(IntArrayList::new, MutableIntList::add, MutableIntList::addAll);
Note: I am a contributor to Eclipse Collections.
注意:我是 Eclipse Collections 的贡献者。
回答by Ida Buci?
You could also use mapToObj() on a Stream, which takes an IntFunction and returns an object-valued Stream consisting of the results of applying the given function to the elements of this stream.
您还可以在 Stream 上使用 mapToObj(),它接受一个 IntFunction 并返回一个对象值 Stream,该对象值 Stream 由将给定函数应用于此流的元素的结果组成。
List<Integer> intList = myIntStream.mapToObj(i->i).collect(Collectors.toList());
回答by Vikash
Find the folowing example of finding square of each int element using Java 8 :-
查找以下使用 Java 8 查找每个 int 元素的平方的示例:-
IntStream ints = Arrays.stream(new int[] {1,2,3,4,5});
List<Integer> intsList = ints.map(x-> x*x)
.collect(ArrayList<Integer>::new, ArrayList::add, ArrayList::addAll);
回答by Harry Jones
You can use the collect method:
您可以使用 collect 方法:
IntStream.of(1, 2, 3).collect(ArrayList::new, List::add, List::addAll);
In fact, this is almost exactly what Java is doing when you call .collect(Collectors.toList()) on an object stream:
事实上,当你在对象流上调用 .collect(Collectors.toList()) 时,这几乎就是 Java 所做的:
public static <T> Collector<T, ?, List<T>> toList() {
return new Collectors.CollectorImpl(ArrayList::new, List::add, (var0, var1) -> {
var0.addAll(var1);
return var0;
}, CH_ID);
}
Note: The third parameter is only required if you want to run parallel collection; for sequential collection providing just the first two will suffice.
注意:第三个参数只有在运行并行收集时才需要;对于顺序收集,仅提供前两个就足够了。