gpt4 book ai didi

java - 将 Hashmap 拆分为两个较小的 Map

转载 作者:行者123 更新时间:2023-12-02 09:45:08 31 4
gpt4 key购买 nike

我有一个 HashMap ,其 K、V 值为,我想将其拆分为两个子图。

HashMap<Long,JSONObject>

一种方法是我发现我们可以使用树形图并进行子映射。

TreeMap<Integer, Integer> sorted = new TreeMap<Integer, Integer>(bigMap);

SortedMap<Integer, Integer> zeroToFortyNine = sorted.subMap(0, 50);
SortedMap<Integer, Integer> fiftyToNinetyNine = sorted.subMap(50, 100);

但问题是我没有获得 jsonObject 的 subMap,而我只想使用 HashMap 来实现。

谢谢

最佳答案

您可以使用Java 8 Streaming API:

Map<Long, JSONObject> map = ...;
AtomicInteger counter = new AtomicInteger(0);
Map<Boolean, Map<Long, JSONObject>> collect = map.entrySet()
.stream()
.collect(Collectors.partitioningBy(
e -> counter.getAndIncrement() < map.size() / 2, // this splits the map into 2 parts
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue
)
));

这会将 map 分为两半,第一个 (map.get(true)) 包含中间下方的所有元素,第二个 (map.get(false)) 一半包含从中间向上的所有元素。

关于java - 将 Hashmap 拆分为两个较小的 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50871243/

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