如何在Java中分割一个HashMap [英] How to split an HashMap in Java

查看:1067
本文介绍了如何在Java中分割一个HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在我的例子中,我有一个包含100个元素的HashMap,我希望能够将HashMap分解为更小的子地图。创建2个(或更多)较小的HashMaps,第一个包含从0到49的条目,第二个包含从50到99的条目。

 映射< Integer,Integer> bigMap = new HashMap< Integer,Integer>(); 

//应该包含'bigMap'的0到49的条目
Map< Integer,Integer> smallMap1 = new HashMap< Integer,Integer>();


//应包含来自'bigMap'的50到99的条目
映射< Integer,Integer> smallMap2 = new HashMap< Integer,Integer>();

有什么建议吗?非常感谢!

解决方案

您是否必须使用 HashMap

TreeMap 对于这类事情真的很好。这里有一个例子。

  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);


I was wondering if it is possible to split a HashMap into smaller sub-maps.

In my case I have a HashMap of 100 elements and I would like to create 2 (or more) smaller HashMaps from the original one, the first containing the Entries from 0 to 49, the second containing the Entries from 50 to 99.

Map <Integer, Integer> bigMap = new HashMap <Integer, Integer>();

//should contains entries from 0 to 49 of 'bigMap'
Map <Integer, Integer> smallMap1 = new HashMap <Integer, Integer>(); 


//should contains entries from 50 to 99 of 'bigMap'
Map <Integer, Integer> smallMap2 = new HashMap <Integer, Integer>();

Any suggestions? Many thanks!

解决方案

Do you have to use HashMap?

TreeMap is really good for this kind of things. Here's an example.

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);

这篇关于如何在Java中分割一个HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆