java之list均分

有時候,有需求如下:需要對一個list進行分包,比如100個數據,分成10包,每個包10個數據。

代碼實現如下:

        List<Integer> ListData = new ArrayList<>();
        ListData.add(1);
        ListData.add(2);
        ListData.add(3);
        ListData.add(4);

        int iPacket = 2;
        int iCount = ListData.size()/iPacket;
        int iRemaind = ListData.size() % iPacket;

        List<List<Integer>> AverageInfo = new ArrayList<>();

        for (int i =0;i<iCount;i++){
            List<Integer> tempInfo =ListData.subList(i*iPacket,(i+1)*iPacket);
            AverageInfo.add(tempInfo);
        }

        if (iRemaind>0){
            List<Integer> tempInfo  = ListData.subList(iCount*iPacket,iCount*iPacket+iRemaind);
            AverageInfo.add(tempInfo);
        }

        for (List<Integer> item :AverageInfo){
            Log.i("test","listAverage");
            for (Integer i :item){
                Log.i("test","item:"+i);
            }
        }

輸出結果如下:成功實現了分包

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章