I have a project requirement where I have to split a HashMap of around 60-70 entries into multiple HashMaps
. The critical number of the split is 30 due to performance reasons because eventually this HashMap
is going to be wrapped in a customer Request
object and sent in an API call. The receiving end during performance testing found that 30 is the only number they can take for good performance.
So, I have to split the HashMap
of 70 subscribers into sub-HashMaps
of - 30, 30, 10.
Since HashMaps
do not have methods like - subMap()
or tailMap()
- I am thinking of converting the HashMap
into TreeMap
. Here's my implementation:
checkAndSplitSubscribers(Map<String, Type> originalMap) throws Exception { List<Map<String, Type>> listOfSplitMaps = new ArrayList<Map<String, Type>>(); int criticalNumber = 30; (Although this will be configurable) try { TreepMap<String, Type> treeMap = new TreeMap<String, Type> (originalMap); List<String> keys = new ArrayList<String> (originalMap.keySet()); final int originalMapSize = treeMap.size(); for (int i = 0; i < originalMapSize; i += criticalNumber) { if (i + criticalNumber < originalMapSize) { listOfSplitMaps.add(treeMap.subMap(keys.get(i), keys.get(i + criticalNumber)); } else { listOfSplitMaps.add(treeMap.tailMap(keys.get(i)); } } } catch (Exception e) { throw e; } return listOfSplitMaps; }
I want to ask if there is anything wrong with this implementation? Is converting HashMap
to TreeMap
mid way of the code really a bad programming practice? Or if there's any better way to achieve the above, please suggest (I have searched and gone through almost all splitting hashmap questions on SO but I did not find any answer to my satisfaction).