如何将collect从Java8流的中间移除到新流中?

如何将collect从Java8流的中间移除到新流中?,java,java-8,java-stream,Java,Java 8,Java Stream,我正在处理一个Java8流。我需要在地图上按两个键分组。然后将这些键及其值放入一个新函数中 有没有办法跳过采集器并重新读取 graphs.stream() .map(AbstractBaseGraph::edgeSet) .flatMap(Collection::stream) .collect(Collectors.groupingBy( graph::getEdgeSource, Collectors.groupingBy(

我正在处理一个Java8流。我需要在地图上按两个键分组。然后将这些键及其值放入一个新函数中

有没有办法跳过
采集器
并重新读取

graphs.stream()
    .map(AbstractBaseGraph::edgeSet)
    .flatMap(Collection::stream)
    .collect(Collectors.groupingBy(
        graph::getEdgeSource,
        Collectors.groupingBy(
            graph::getEdgeTarget,
            Collectors.counting()
        )
    ))
    .entrySet().stream()
    .forEach(startEntry ->
        startEntry.getValue().entrySet().stream()
            .forEach(endEntry ->
                graph.setEdgeWeight(
                    graph.addEdge(startEntry.getKey(), endEntry.getKey()),
                    endEntry.getValue() / strains
                )));

不,您必须有某种中间数据结构来累积计数。根据graph和edge类的编写方式,您可以尝试将计数直接累加到graph中,但这样做的可读性较低,而且更脆弱

请注意,您可以使用以下命令更简洁地迭代中间映射:

如果您不喜欢“地图地图”方法,也可以将计数收集到
Map
而不是
Map

graphs.stream()
    .map(AbstractBaseGraph::edgeSet)
    .flatMap(Collection::stream)
    .collect(groupingBy(
            edge -> Arrays.asList(
                graph.getEdgeSource(edge), 
                graph.getEdgeTarget(edge)
            ),
            counting()
    ))
    .forEach((nodes, count) -> 
        graph.setEdgeWeight(graph.addEdge(nodes.get(0), nodes.get(1)), count/strains)
    );

“您必须有某种中间数据结构来累积计数”,除非输入已经排序或可以分组方式遍历,允许您一次发送一个组作为流元素。是的,有些源允许直接计算计数,就像有些目标允许直接累积计数一样,但这不是OP要问的。
graphs.stream()
    .map(AbstractBaseGraph::edgeSet)
    .flatMap(Collection::stream)
    .collect(groupingBy(
            edge -> Arrays.asList(
                graph.getEdgeSource(edge), 
                graph.getEdgeTarget(edge)
            ),
            counting()
    ))
    .forEach((nodes, count) -> 
        graph.setEdgeWeight(graph.addEdge(nodes.get(0), nodes.get(1)), count/strains)
    );