我有一个哈希图,其 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);
Run Code Online (Sandbox Code Playgroud)
但问题是我没有获得 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
)
));
Run Code Online (Sandbox Code Playgroud)
这会将地图分为两半,第一半 ( map.get(true)) 包含中间以下的所有元素,第二map.get(false)半 ( ) 包含中间向上的所有元素。
从你的问题看来,你并不关心分割的标准,你只是想把它分成两半。下面的解决方案将相应地起作用。只需创建一个计数器并在计数器<(原始哈希图的大小)/2时插入前半部分哈希图,当计数器>(原始哈希图的大小)/2时,插入到后半部分哈希图。
HashMap<Integer,JSONObject> hmap;
HashMap<Integer,JSONObject> halfhmap1=new HashMap<>();
HashMap<Integer,JSONObject> halfhmap2=new HashMap<>();
int count=0;
for(Map.Entry<Long, JSONObject> entry : map.entrySet()) {
(count<(hmap.size()/2) ? halfhmap1:halfhmap2).put(entry.getKey(), entry.getValue());
count++;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20160 次 |
| 最近记录: |