How to split an HashMap in Java
Do you have to use HashMap
?
TreeMap
is really good for this kind of things. Here's an example (note that 0, 50, and 99 are map keys, not indices):
TreeMap<Integer, Integer> sorted = new TreeMap<Integer, Integer>(bigMap);
SortedMap<Integer, Integer> zeroToFortyNine = sorted.subMap(0, 50); // toKey inclusive, fromKey exclusive
SortedMap<Integer, Integer> fiftyToNinetyNine = sorted.subMap(50, true, 99, true);
You'll basically need to iterate over the entries in bigMap
, and make a decision as to whether they should be added to smallMap1
or smallMap2
.