java - 将 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
)
));
这会将地图收集成 2 个半部分,第一个 ( map.get(true)
) 包含从中间以下的所有元素,第二个 ( map.get(false)
) 包含从中间向上的所有元素。
推荐阅读
- jsp - 无法让 JSTL 标记与 Tomcat 9 一起使用,尝试了所有解决方案均无效
- python - Jupyter 仪表板显示/渲染问题 - 小部件重叠
- php - MySQL 查询没有显示结果
- jquery - JSON 中位置 1 的意外标记 o 或无法读取未定义的属性“0”
- unity3d - Unity Particles 不适用于自定义脚本
- javascript - Nuxt 子路由重新渲染整个页面
- url - 我可以修改浏览器使其只能访问一个网站吗?
- python - 在其中访问 Jupyter Noteook 的 JSON
- go - 查找整数位数的最快方法?
- autodesk-forge - 映射到 Forge Viewer