【问题标题】:What's the efficient way to group this list objects?对此列表对象进行分组的有效方法是什么?
【发布时间】:2010-10-22 19:06:58
【问题描述】:

我有一个对象列表,对象的数量是随机的。

我想请高效代码以每组有 4 个对象(最后一组少于/等于 4 个对象)的方式对对象进行分组。我首先需要知道组的数量,然后对于每个组,我将遍历对象。

【问题讨论】:

  • 你真的需要回到你的老问题并接受一些答案。

标签: java


【解决方案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) {
        // ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 2018-10-06
    相关资源
    最近更新 更多