tnas
tnas

Reputation: 511

StreamSupport collector and java 7

I'm trying to use StreamSupport in order to explore stream on Java 7. I've added streamsupport-1.5.4.jar to my project and written a 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'm receiving the following error:

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

I've tried to apply the hint proposed by Eclipse

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

but it has not solved the problem.

Does someone have any idea? Thanks.

Upvotes: 3

Views: 958

Answers (1)

Stefan Zobel
Stefan Zobel

Reputation: 3212

The streamsupport entry points to receive a java8.util.stream.Stream from a java.util.Collection are mainly

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 can't use java.util.Collection#stream() because that

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

b) it mingles java.util.stream.Collectors with your (correct) java8.util.stream.Collectors import

(Disclaimer: I'm the maintainer of streamsupport)

Upvotes: 3

Related Questions