如何从 java 8 流中删除一个收集到新流中?
How to remove a collect into a new stream from the middle of a java 8 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
)));
不,您必须有某种中间数据结构来累积计数。根据您的图形和边 类 的编写方式,您可以尝试将计数直接累加到图形中,但这会降低可读性并且更脆弱。
请注意,您可以使用 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)
);
我正在处理 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
)));
不,您必须有某种中间数据结构来累积计数。根据您的图形和边 类 的编写方式,您可以尝试将计数直接累加到图形中,但这会降低可读性并且更脆弱。
请注意,您可以使用 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)
);