Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 248
tnas Avatar asked Apr 10 '26 00:04

tnas


1 Answers

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)

like image 95
Stefan Zobel Avatar answered Apr 11 '26 15:04

Stefan Zobel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!