Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter a stream of integers into a list?

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?

like image 722
dave Avatar asked Jul 09 '17 08:07

dave


1 Answers

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));
like image 121
Eran Avatar answered Sep 20 '22 13:09

Eran