我在看的文檔爲IntStream
,我看到一個toArray
方法,但是沒有辦法直接去List<Integer>
如何將Java 8 IntStream轉換爲列表?
當然有辦法一個Stream
轉換爲List
?
我在看的文檔爲IntStream
,我看到一個toArray
方法,但是沒有辦法直接去List<Integer>
如何將Java 8 IntStream轉換爲列表?
當然有辦法一個Stream
轉換爲List
?
IntStream.boxed
變成一個IntStream
爲Stream<Integer>
,你可以再collect
到一個列表:
theIntStream.boxed().collect(Collectors.toList())
您可以利用現有的原始集合在Eclipse Collections和避免裝箱。
MutableIntList list =
IntStream.range(1, 5)
.collect(IntArrayList::new, MutableIntList::add, MutableIntList::addAll);
注:我是Eclipse Collections的貢獻者。
雖然Eclipse集合通常很有幫助,但它看起來並不像它讓所有事情都變得更簡單:) – Ben
您還可以在Stream上使用mapToObj(),它接受一個IntFunction並返回一個對象值流,該流包含將給定函數應用於此流的元素的結果。
List<Integer> intList = myIntStream.mapToObj(i->i).collect(Collectors.toList());
嘗試此鏈接:http://stackoverflow.com/questions/14830313/retrieving-a-list-from-a-java-util-stream-stream-in-java8 –