Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to pull items from an array 10 at a time

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!

like image 216
mkki Avatar asked Feb 10 '16 06:02

mkki


2 Answers

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
like image 62
Titus Avatar answered Sep 22 '22 01:09

Titus


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.

like image 37
Mustansar Saeed Avatar answered Sep 24 '22 01:09

Mustansar Saeed