Thursday, June 27, 2013

Sub-collection or batch creation from a big collection

Requirement is I have a list like [a, b, c, d, e] and I want to create batch/sublist of size 2 (last sublist can be of size 1 or 2).
I.e. the output should be [[a, b], [c, d], [e]].

One options is to use java.util.List.sublist() method which returns the subcollection for given index which you need to maintain.
Google's Guava APIs have lot of such utility methods using which you can achieve the needed thing in one line.

Example:

import java.util.Arrays;
import java.util.List;

import com.google.common.collect.Lists;

public class Junk {
   
    public static void main(String[] args) {
        List<String> stringCollection = Arrays.asList(
            new String[] {"a" , "b", "c", "d", "e"});

        int batchSize = 2;

        List<List<String>> subBatches = Lists.partition(stringCollection, batchSize);
       
        for (List<String> subBatch : subBatches) {
            // Do what you want with each sub batch!
        }
    }
   

No comments:

Post a Comment