This was one of the functions that performed my work, I hope that it will be useful to others. This works regardless of the object / primitive stored as the key.
The TreeMap approach proposed above will only work if the keys are primitives, ordered, and the exact sequence of the index.
public List<Map<Integer, EnrichmentRecord>> splitMap(Map<Integer, EnrichmentRecord> enrichmentFieldsMap, int splitSize) { float mapSize = enrichmentFieldsMap.size(); float splitFactorF = splitSize; float actualNoOfBatches = (mapSize / splitFactorF); double noOfBatches = Math.ceil(actualNoOfBatches); List<Map<Integer, EnrichmentRecord>> listOfMaps = new ArrayList<>(); List<List<Integer>> listOfListOfKeys = new ArrayList<>(); int startIndex = 0; int endIndex = splitSize; Set<Integer> keys = enrichmentFieldsMap.keySet(); List<Integer> keysAsList = new ArrayList<>(); keysAsList.addAll(keys); for (int i = 0; i < noOfBatches; i++) { listOfListOfKeys.add(keysAsList.subList(startIndex, endIndex)); startIndex = endIndex; endIndex = (int) (((endIndex + splitSize) > mapSize) ? mapSize : (endIndex + splitSize)); } for(List<Integer> keyList: listOfListOfKeys){ Map<Integer,EnrichmentRecord> subMap = new HashMap<>(); for(Integer key: keyList){ subMap.put(key,enrichmentFieldsMap.get(key)); } listOfMaps.add(subMap); } return listOfMaps; }
Nizamudeen karimudeen
source share