StreamSupport and java 7 collector

I am trying to use StreamSupport to explore a stream in Java 7. I added streamsupport-1.5.4.jar

to my project and wrote code like this:

import java8.util.stream.Collectors;

public class FinantialStatement {

    private List<Rubric> values;

    public List<Rubric> getConsolidatedRubrics() {
        List<Rubric> rubrics = values.stream().sorted((Rubric r1, Rubric r2) -> r1.getOrder().compareTo(r2.getOrder())).collect(Collectors.toCollection(ArrayList::new));
        return rubrics;
    }
}

      

I am getting the following error:

Type mismatch: cannot convert from Collector<Object,capture#1-of
?,Collection<Object>> to Collector<? super Rubric,A,R>

      

I tried to apply the hint suggested by Eclipse

Add cast to '(Collector<? super Rubric, A, R>)'

      

but it didn't solve the problem.

Does anyone have any ideas? Thank.

+3


source to share


1 answer


streamsupport entry points to receive java8.util.stream.Stream

from java.util.Collection

basically

1) java8.util.stream.StreamSupport # stream

2) java8.util.stream.StreamSupport # parallelStream

So your code snippet should look like this:

import java.util.ArrayList;
import java.util.List;

import java8.util.stream.Collectors;
import java8.util.stream.StreamSupport;

public class FinantialStatement {

    private List<Rubric> values;

    public List<Rubric> getConsolidatedRubrics() {
        List<Rubric> rubrics = StreamSupport.stream(values)
                .sorted((Rubric r1, Rubric r2) -> r1.getOrder().compareTo(r2.getOrder()))
                .collect(Collectors.toCollection(ArrayList::new));
        return rubrics;
    }
}

      



Edit

Obviously you cannot use java.util.Collection#stream()

because

a) is a method that only exists in Java 8 and

b) it mixes java.util.stream.Collectors

with your (correct) java 8 .util.stream.Collectors import

(Disclaimer: I support streamsupport)

+3


source







All Articles