2010-10-22 118 views
0

我有一個對象列表,對象的數量是隨機的。分組這個列表對象的有效方法是什麼?

我想問高效的代碼,以每個組有4個對象(最後一組少於/等於4個對象)的方式對對象進行分組。我需要先知道組的數量,然後對每個組,我將遍歷這些對象。

+7

你真的需要回到你的舊問題並接受一些答案。 – msandiford 2010-10-22 11:00:36

回答

1
List<E> list = ...; 

int groupSize = 4; 
int groupCount = (int) Math.ceil(list.size()/(float) groupSize); 

for (int i = 0; i < groupCount; i++) { 
    // Most List implementations have an effecient subList implementation 
    List<E> group = list.subList(
      i * groupSize, // "from" index (inclusive) 
      Math.min((i + 1) * groupSize, list.size()), // "to" index (exclusive) 
     ); 

    for (E element : group) { 
     // ... 
    } 
} 
相關問題