2010-10-22 59 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) { 
     // ... 
    } 
} 
相关问题