Лучший способ вытащить элементы из массива 10 за раз
У меня есть ArrayList, который может содержать неограниченное количество объектов. Мне нужно вытащить 10 предметов за раз и сделать над ними операции.
то, что я могу себе представить, это.
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
}
какие мысли? Спасибо!
3 ответов
вы можете сделать что-то вроде этого:
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>();
}
}
проблема с вашей текущей реализацией заключается в том, что вы создаете batchList
на каждой итерации вам нужно будет объявить этот список (batchList
) вне цикла. Что-то вроде:
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
здесь Guava library
предоставлен Google
что облегчает различные функции.
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}}
ответ взят из https://stackoverflow.com/a/9534034/3027124 и https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists
надеюсь, что это помогает.
чтобы вытащить элемент из ArrayList:ArrayList.remove(0)
// clone the list first if you need the values in the future:
ArrayList<object> cloned = new ArrayList<>(list);
while(!list.isEmpty()){
object[] tmp = new object[10];
try{
for(int i = 0; i < 10; i++) tmp[i] = list.remove(0);
}catch(IndexOutOfBoundsException e){
// end of list reached. for loop is auto broken. no need to do anything.
}
// do something with tmp, whose .length is <=10
}