将value为list的map按照指定数量分割

需求描述:
        首先是有一个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]}]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值