如何将Java 8 IntStream转换为列表?

时间:2022-10-30 14:54:19

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

Surely there is a way to convert a Stream to a List?

肯定有办法将流转换成列表吗?

3 个解决方案

#1


361  

IntStream.boxed turns an IntStream into a Stream<Integer>, which you can then collect into a list:

IntStream。框化将IntStream转换为 ,然后您可以将其收集到列表中:

theIntStream.boxed().collect(Collectors.toList())

#2


11  

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.

您还可以在流上使用mapToObj(),它接受IntFunction并返回一个对象值流,该流包含将给定函数应用到流的元素的结果。

List<Integer> intList = myIntStream.mapToObj(i->i).collect(Collectors.toList());

#3


7  

You can use primitive collections available in Eclipse Collections and avoid boxing.

您可以使用Eclipse集合中可用的原始集合,并避免装箱。

MutableIntList list = 
    IntStream.range(1, 5)
    .collect(IntArrayList::new, MutableIntList::add, MutableIntList::addAll);

Note: I am a contributor to Eclipse Collections.

注意:我是Eclipse集合的贡献者。

#1


361  

IntStream.boxed turns an IntStream into a Stream<Integer>, which you can then collect into a list:

IntStream。框化将IntStream转换为 ,然后您可以将其收集到列表中:

theIntStream.boxed().collect(Collectors.toList())

#2


11  

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.

您还可以在流上使用mapToObj(),它接受IntFunction并返回一个对象值流,该流包含将给定函数应用到流的元素的结果。

List<Integer> intList = myIntStream.mapToObj(i->i).collect(Collectors.toList());

#3


7  

You can use primitive collections available in Eclipse Collections and avoid boxing.

您可以使用Eclipse集合中可用的原始集合,并避免装箱。

MutableIntList list = 
    IntStream.range(1, 5)
    .collect(IntArrayList::new, MutableIntList::add, MutableIntList::addAll);

Note: I am a contributor to Eclipse Collections.

注意:我是Eclipse集合的贡献者。