I am trying to process a stream of Integers
and collect the integers that match a predicate (via the compare()
function) into a list. Here's a rough outline of the code I've written.
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 does not compile and I cannot make sense of the compiler error for the line highlighted:
The method collect(Supplier<R>, ObjIntConsumer<R>, BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,capture#1-of ?,Collection<Object>>)
Any suggestions?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With