我正在研究Java 8流.我需要在地图中按2个键分组.然后将这些键及其值放入新函数中.
有没有办法跳过收集器并再次读出?
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
)));
解决方法:
不,您必须具有某种中间数据结构才能累积计数.根据图形和边沿类的编写方式,您可以尝试将计数直接累加到图形中,但这会降低可读性和脆性.
请注意,您可以使用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>如果您不喜欢map-of-maps方法:
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)
);
标签:java-8,java-stream,java
来源: https://codeday.me/bug/20191120/2042261.html