从@Nizamudeen Karimudeen 的回答构建,如果没有大量的重写,我就无法开始工作......这个方法适用于其中包含任何类的任何 HashMap。
因此,假设您要拆分的 Map 定义如下:
Map<String, MyClass> myMap = new HashMap<>();
如果您希望将其拆分为 20 个单独的地图,您只需将其拆分为:
List<Map<String, MyClass>> splitMapList = splitMap(myMap, 20);
然后要使用每个单独的地图,您可以像这样遍历它们:
for (Map<String, MyClass> mySplitMap : splitMapList) {
for(String key : mySplitMap.keySet()) {
MyClass myClass = mySplitMap.get(key);
}
}
或者您可以通过列表的索引等直接引用它们。
Map<String, MyClass> subMap = splitMapList.get(3);
这是方法:
public static List<Map<KeyClass, ValueClass>> splitMap(Map<KeyClass, ValueClass> originalMap, int splitSize) {
int mapSize = originalMap.size();
int elementsPerNewMap = mapSize / splitSize;
List<Map<KeyClass, ValueClass>> newListOfMaps = new ArrayList<>(); //Will be returned at the end after it's built in the final loop.
List<List<KeyClass>> listOfMapKeysForIndexing = new ArrayList<>(); //Used as a reference in the final loop.
List<KeyClass> listOfAllKeys = new ArrayList<>(originalMap.keySet());
int maxIndex = listOfAllKeys.size() - 1; //We use this in the first loop to make sure that we never exceed this index number or we will get an index out of range.
int startIndex = 0;
int endIndex = elementsPerNewMap;
for (int i = 0; i < splitSize; i++) { //Each loop creates a new list of keys which will be the entire set for a new subset of maps (total number set by splitSize.
listOfMapKeysForIndexing.add(listOfAllKeys.subList(startIndex, endIndex));
startIndex = Math.min((endIndex + 1), maxIndex);//Start at the next index, but don't ever go past the maxIndex or we get an IndexOutOfRange Exception
endIndex = Math.min((endIndex + elementsPerNewMap), maxIndex);//Same thing for the end index.
}
/*
* This is where we use the listOfMapKeysForIndexing to create each new Map that we add to the final list.
*/
for(List<KeyClass> keyList: listOfMapKeysForIndexing){
Map<KeyClass,ValueClass> subMap = new HashMap<>(); //This should create a quantity of these equal to the splitSize.
for(KeyClass key: keyList){
subMap.put(key,originalMap.get(key));
}
newListOfMaps.add(subMap);
}
return newListOfMaps;
}