Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts

Jan 18, 2014

Dividing list of objects into sub lists

Some times we may need to break down the list of objects/primitives from a master/parent list and create objects/primitives sub lists.

Say, we have a list of 2000 employee numbers , and we would like to divide them into 20 sub lists of 200 employee numbers each. then the following method comes handy. it's a kind of utility method.

   /**
    * @param parentList
    * @param childListSize
    * @return
    */

    List<List<Integer>> createSubLists(List<Integer> parentList,
           int childListSize) {
        List<List<Integer>>listOfSublists = new ArrayList<List<Integer>>();
      
       int parentListSize = parentList.size();
       System.out.println("Size of the parent list:["+parentListSize+"]");
       for(int parentIndex = 0; parentIndex < parentListSize;){
           List<Integer> tempChildList = new ArrayList<Integer> ();
           for(int childIndex = 0; childIndex < childListSize ; childIndex++ ){
               if(parentIndex >= parentListSize){
                   break;
               }
               tempChildList.add(parentList.get(parentIndex++));
           }
           listOfSublists.add(tempChildList);
       }
       return listOfSublists;
   }



Execution:

Input :

parentList : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
childListSize : 5

Output:

Size of the parent list:[30]
sub list size desired : 5
Number of sub lists divided : 6
 

List 1: [1,2,3,4,5]
List 2: [6,7,8,9,10]
List 3: [11,12,13,14,15]
List 4: [16,17,18,19, 20]
List 5: [21,22,23,24,25]
List 6: [26,27,28,29,30]


we can use this method for other data types also by making the list as generic.

Main Differences Between SVN and Git