How to filter a stream of integers to a list?
I am trying to process a stream Integers
and collect integers that match a predicate (via a function compare()
) into a list. Here's a rough outline of the code I wrote.
private List<Integer> process() {
Z z = f(-1);
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.collect(Collectors.toCollection(ArrayList::new)); // Error on this line
}
private boolean compare(Z z1, Z z2) { ... }
private Z f(int i) { ... }
Unfortunately my solution doesn't compile and I can't figure out the compiler error for the highlighted line:
Collection method (Provider <R>, ObjIntConsumer <R>, BiConsumer <R, R>) in IntStream type is not applicable for arguments (Collector <Object, capture # 1-of ?, Collection <Object β)
Any suggestions?
source to share
IntStream
does not contain a method collect
that takes one type argument Collector
. Stream
does. Therefore, you must convert yours IntStream
to Stream
objects.
You can IntStream
in 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 packed into an integer.
or
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.mapToObj(Integer::valueOf)
.collect(Collectors.toCollection(ArrayList::new));
source to share