需求描述: 首先是有一个value为list的map对象,需要保证map对象中的list中数据量不能超过某个指定数 量,如果超过了,将map按照value中数量分割为多个map public List<Map<String, List<String>>> splitMap(Map<String, List<String>> mapObj, int limit) {
List<Map<String, List<String>>> result = new ArrayList<>(); if (mapObj==null || mapObj.size()==0) { return result; } Integer totalLength = 0; for (List<String> list : mapObj.values()) { totalLength += list.size(); } int maxNumber=totalLength/limit+1; int cycleNumber=0;//记录次数,防止无限循环 Set<String> set = mapObj.keySet(); List<String> list=new ArrayList<>(set); int j=0;//目前已解析map中的list下标 int currentLength = 0;//新生成map中的list下标 int i=0;//解析中的list数据下标 do { Map<String, List<String>> currentMap = new HashMap<>(); for (; j <list.size(); j++) { String key = list.get(j); List<String> value = mapObj.get(key); if (currentLength == limit) { i = 0; currentLength=0; break; } if (currentLength + value.size() -i <= limit) { currentMap.put(key, value.subList(i, value.size())); currentLength = currentLength+value.size()-i; i=0; } else if (currentLength+limit+i<= value.size()){ currentMap.put(key, value.subList(i, i+limit)); currentLength = 0; i+=limit; break; }else { i = limit - currentLength; currentMap.put(key, value.subList(0, i)); currentLength=0; break; } } result.add(currentMap); cycleNumber++; }while (j<list.size()&&cycleNumber<=maxNumber); return result;
}
举例:
存在一个map为
{0=[0|0, 0|1, 0|2, 0|3, 0|4, 0|5, 0|6, 0|7, 0|8, 0|9], 1=[1|1, 1|2, 1|3, 1|4, 1|5, 1|6, 1|7, 1|8, 1|9], 2=[2|2, 2|3, 2|4, 2|5, 2|6, 2|7, 2|8, 2|9], 3 =[3|3, 3|4, 3|5, 3|6, 3|7, 3|8, 3|9], 4=[4|4, 4|5, 4|6, 4|7, 4|8, 4|9], 5=[5|5, 5|6, 5|7, 5|8, 5|9]}
将其分割为每个map中只有6个数据
List<Map<String, List<String>>> maps = splitMap(mapObj, 6);
输出结果为:分割为8个map对象
[{0=[0|0, 0|1, 0|2, 0|3, 0|4, 0|5]}, {0=[0|6, 0|7, 0|8, 0|9], 1=[1|1, 1|2]}, {1=[1|1, 1|2, 1|3, 1|4, 1|5, 1|6]}, {1=[1|7, 1|8, 1|9], 2=[2|2, 2|3, 2|4]}, {2=[2|5, 2|6, 2|7, 2|8, 2|9], 3=[3|3]}, {3=[3|4, 3|5, 3|6, 3|7, 3|8, 3|9]}, {4=[4|4, 4|5, 4|6, 4|7, 4|8, 4|9]}, {5=[5|5, 5|6, 5|7, 5|8, 5|9]}]