How to split array list into equal parts?

前端 未结 9 1204
攒了一身酷
攒了一身酷 2020-11-29 07:20

Is there anyway to split ArrayList into different parts without knowing size of it until runtime? I know there is a method called:

list.subList(a,b);
         


        
相关标签:
9条回答
  • 2020-11-29 08:05
    listSize = oldlist.size();
    chunksize =1000;
    chunks = list.size()/chunksize;
    ArrayList subLists;
    ArrayList finalList;
    int count = -1;
    for(int i=0;i<chunks;i++){
         subLists = new ArrayList();
         int j=0;
         while(j<chunksize && count<listSize){
            subList.add(oldList.get(++count))
            j++;
         }
         finalList.add(subLists)
    }
    

    You can use this finalList as it contains the list of chuncks of the oldList.

    0 讨论(0)
  • 2020-11-29 08:12

    If you're constrained by PL/SQL in limits then you want to know how to split a list into chunks of size <=n, where n is the limit. This is a much simpler problem as it does not require knowing the size of the list in advance.

    Pseudocode:

    for (int n=0; n<list.size(); n+=limit)
    {
        chunkSize = min(list.size,n+limit);
        chunk     = list.sublist(n,chunkSize);
        // do something with chunk
    }
    
    0 讨论(0)
  • 2020-11-29 08:13

    generic method for your help :

    private static List<List<Object>> createBatch(List<Object> originalList,
            int chunkSize) {
        List<List<Object>> listOfChunks = new ArrayList<List<Object>>();
        for (int i = 0; i < originalList.size() / chunkSize; i++) {
            listOfChunks.add(originalList.subList(i * chunkSize, i * chunkSize
                    + chunkSize));
        }
        if (originalList.size() % chunkSize != 0) {
            listOfChunks.add(originalList.subList(originalList.size()
                    - originalList.size() % chunkSize, originalList.size()));
        }
        return listOfChunks;
    
    0 讨论(0)
提交回复
热议问题