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

dave :

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?

Eran :

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));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475824&siteId=1