How do I filter a stream of integers into a list?
IntStream
doesn't contain a collect
method that accepts a single argument of type Collector
. Stream
does. Therefore you have to convert your IntStream
to a Stream
of objects.
You can either box the IntStream
into a Stream<Integer>
or use mapToObj
to achieve the same.
For example:
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
boxed()
will return a Stream consisting of the elements of this stream, each boxed to an Integer.
or
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.mapToObj(Integer::valueOf)
.collect(Collectors.toCollection(ArrayList::new));
Or you can specify the Supplier, Accumulator and Combiner
yourself:
IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);