如何在Java中拆分HashMap

RNO*_*RNO 8 java hashmap

我想知道是否可以将HashMap拆分成更小的子地图.

在我的例子中,我有一个100个元素的HashMap,我想从原始的HashMap创建2个(或更多)小HashMaps,第一个包含从0到49的条目,第二个包含从50到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>();
Run Code Online (Sandbox Code Playgroud)

有什么建议?非常感谢!

sha*_*kan 13

你必须使用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);
Run Code Online (Sandbox Code Playgroud)

  • 这个答案令人困惑:它不考虑条目索引而是直接考虑密钥.它不能被称为_a分裂map_的解决方案. (6认同)
  • 这个答案只适用于具有从0到99的数字作为键的映射.方法`subMap(a,b)`的参数不是指元素的数量,而是指键的值.如果您的地图包含从500到599的100个数字,`subMap(0,49)`将是空的,以及als`subMap(50,99)`.唯一的完整地图是`subMap(100,99999999)`. (3认同)
  • downvoter关注为什么这不是一个好的答案? (2认同)