gpt4 book ai didi

java - 如何从 Java 8 流的中间删除一个收集到新流中?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:43:20 25 4
gpt4 key购买 nike

我正在处理 Java 8 流。我需要在 map 中按 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>>如果您不喜欢 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)
);

关于java - 如何从 Java 8 流的中间删除一个收集到新流中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30629209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com