栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Map拆分成子Map

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Map拆分成子Map

    private static  List> mapChunk(Map map, int chunkSize){
        if(Objects.isNull(map) || map.isEmpty()){
            //空map,无法拆分
            return Collections.emptyList();
        }

        List> list = Lists.newArrayListWithExpectedSize(chunkSize);
        if(chunkSize <= 1){
            //拆分数<=1, 直接添加并返回
            list.add(map);
            return list;
        }

        Iterator> iterator = map.entrySet().iterator();
        int chunkIndex = 0; //当前分段的下标,[0, chunkSize-1]
        int restCount = map.size()%chunkSize; //平均后剩余
        int totalCount0 = map.size()/chunkSize; //每个分段键值对数量,最后一个分段装入剩余的所有
        int totalCount1 = totalCount0 + 1;
        int totalCount;
        int count = 0; //每个分段的计数
        Map subMap = new HashMap<>();
        while (iterator.hasNext()){
            if(chunkIndex < restCount){
                totalCount = totalCount1; //分不完的部分,给部分分段多分1个, 可保证尽量均匀
            }else{
                totalCount = totalCount0;
            }

            Map.Entry entry = iterator.next();
            if(chunkIndex == chunkSize-1){ //最后一个分段单独处理
                //最后一个分段,有多少添加多少
                subMap.put(entry.getKey(), entry.getValue());
            }else if(count < totalCount){
                //除了最后一个分段,每个分段放totalCount个键值对
                subMap.put(entry.getKey(), entry.getValue());
                count ++; //计次+1
            }else{
                //结束上一个分段
                list.add(subMap); //装满了->加入列表
                chunkIndex ++; //分段个数+1

                //开始下一个分段
                subMap = new HashMap<>(); //新的分段
                subMap.put(entry.getKey(), entry.getValue()); //添加当前键值对
                count = 1; //计数重置为1
            }
        }
        list.add(subMap);

        return list;
    }

    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("a", "1");
        map.put("b", "2");
        map.put("c", "3");
        map.put("d", "4");
        map.put("e", "5");
        map.put("f", "6");
        map.put("g", "7");

        System.out.println(mapChunk(map, 5));
    }

输出:

[{a=1, b=2}, {c=3, d=4}, {e=5}, {f=6}, {g=7}]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/697208.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号