2016-02-10 8 views
6

オブジェクトを無制限に含むことができるArrayListがあります。私は一度に10のアイテムを引っ張り、それらの上で操作を行う必要があります。配列からアイテムを一度に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 
} 

ありがとう! ArrayListから要素をプルする

+0

解決策はまだ動作していませんか? –

+0

それはすべきですが、これを達成するためのよりよい方法について他の人の意見を得たいと思っていました。 – mkki

答えて

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 
+0

私の実装のキャッチに感謝します。私はあなたの実装が好きです。 – mkki

0

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 
} 
1

異なる機能を容易Googleによって提供Guava libraryがあります。 https://stackoverflow.com/a/9534034/3027124https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists

から取ら

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}} 

回答は、この情報がお役に立てば幸いです。

関連する問題