I have an ArrayList that can contain an unlimited amount of objects. I need to pull 10 items at a time and do operations on them.
What I can imagine doing is this.
int batchAmount = 10;
for (int i = 0; i < fullList.size(); i += batchAmount) {
List<List<object>> batchList = new ArrayList();
batchList.add(fullList.subList(i, Math.min(i + batchAmount, fullList.size()));
// Here I can do another for loop in batchList and do operations on each item
}
Any thoughts? Thanks!
You can do something like this:
int batchSize = 10;
ArrayList<Integer> batch = new ArrayList<Integer>();
for (int i = 0; i < fullList.size();i++) {
batch.add(fullList.get(i));
if (batch.size() % batchSize == 0 || i == (fullList.size()-1)) {
//ToDo Process the batch;
batch = new ArrayList<Integer>();
}
}
The problem with your current implementation is that you're creating a batchList
at each iteration, you will need to declare this list (batchList
) outside of the loop. Something like:
int batchAmount = 10;
List<List<object>> batchList = new ArrayList();
for (int i = 0; i < fullList.size(); i += batchAmount) {
ArrayList batch = new ArrayList(fullList.subList(i, Math.min(i + batchAmount, fullList.size()));
batchList.add(batch);
}
// at this point, batchList will contain a list of batches
There is Guava library
provided by Google
which facilitates different functions.
List<Integer> countUp = Ints.asList(1, 2, 3, 4, 5);
List<Integer> countDown = Lists.reverse(theList); // {5, 4, 3, 2, 1}
List<List<Integer>> parts = Lists.partition(countUp, 2); // {{1, 2}, {3, 4}, {5}}
Answer taken from https://stackoverflow.com/a/9534034/3027124 and https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With