首页 > 解决方案 > 将 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

解决方案


您可以使用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)) 包含从中间向上的所有元素。


推荐阅读