我有一个对象列表,对象的数量是随机的。
我想问一下有效的代码,以每个组有4个对象的方式对对象进行分组(最后一组具有小于/等于4个对象)。我首先要知道组的数量,然后对于每个组,我将遍历对象。
答案 0 :(得分: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) {
// ...
}
}