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>
Surely there is a way to convert a Stream
to a List
?
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>
Surely there is a way to convert a Stream
to a List
?
IntStream::boxed
IntStream::boxed
turns an IntStream
into a Stream<Integer>
, which you can then collect
into 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.
Java 16 brought the shorter toList
method. Produces an unmodifiable list. Discussed here.
theIntStream.boxed().toList()
toList
. This is done by placing the following among the imports of the file: static import java.util.stream.Collectors.toList;
. Then the collect call reads just .collect(toList())
. –
Cleanly Collectors
class in Preferences -> Java -> Editor -> Content Assist -> Favorites. After this, you only have to type toLi
at hit Ctr+Space to have the IDE fill in toList
and add the static import. –
Cleanly boxed()
part –
Proscription import java.util.stream.Collectors;
. –
Groceries 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.
List<Integer> intList = myIntStream.mapToObj(i->i).collect(Collectors.toList());
boxed()
is delegating to. –
Boomer You can use primitive collections available in Eclipse Collections and avoid boxing.
MutableIntList list =
IntStream.range(1, 5)
.collect(IntArrayList::new, MutableIntList::add, MutableIntList::addAll);
Note: I am a contributor to Eclipse Collections.
MutableIntList list = IntLists.mutable.withAll(IntStream.range(1, 5))
–
Smith You can use the collect method:
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:
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.
Find the folowing example of finding square of each int element using Java 8 :-
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);
© 2022 - 2024 — McMap. All rights reserved.