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!
}
}
}
Lot of such utility methods are available @
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Lists.html
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect
Lot of such utility methods are available @
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Lists.html
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect
No comments:
Post a Comment