如何从java 8流中间删除一个新的流?

时间:2015-06-03 19:41:50

标签: java java-8 java-stream

我正在研究Java 8流。我需要在地图中按2键分组。然后将这些键及其值放入一个新函数中。

有没有办法跳过Collector并再次阅读?

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

1 个答案:

答案 0 :(得分:3)

不,你必须有某种中间数据结构来累积计数。根据图形和边缘类的编写方式,您可以尝试将计数直接累积到图形中,但这样会更不易读,也不会更脆弱。

请注意,您可以使用Map#forEach

更简洁地迭代中间地图
.forEach((source, targetToCount) -> 
    targetToCount.forEach((target, count) -> 
        graph.setEdgeWeight(graph.addEdge(source, target), count/strains)
    )
);

如果您不喜欢地图地图方法,也可以将计数收集到Map<List<Node>, Long>而不是Map<Node,Map<Node,Long>>

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