编程语言
首页 > 编程语言> > StreamSupport收集器和Java 7

StreamSupport收集器和Java 7

作者:互联网

我正在尝试使用StreamSupport来探索Java 7上的流.我向项目中添加了streamsupport-1.5.4.jar并编写了如下代码:

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

我收到以下错误:

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

我尝试应用Eclipse提出的提示

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

但这并没有解决问题.

有人有什么主意吗?谢谢.

解决方法:

用于从java.util.Collection接收java8.util.stream.Stream的streamsupport入口点主要是

1)java8.util.stream.StreamSupport#stream

2)java8.util.stream.StreamSupport#parallelStream

因此,您的代码段应如下所示:

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

编辑:

显然,您不能使用java.util.Collection#stream(),因为

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

(免责声明:我是streamsupport的维护者)

标签:java-stream,eclipse,java
来源: https://codeday.me/bug/20191111/2019276.html