使用 iterator 实现元素分组的核心做法是:在遍历集合时,根据当前元素的索引或特定条件(如类型、范围)将元素收集到不同的 list 中。具体而言,你可以创建一个包含多个 list 的容器,利用 hasnext() 和 next() 逐个取出元素,并通过逻辑判断将其添加到对应的分组列表中。这样做的好处是无需知道集合的具体实现类(如 arraylist 或 linkedlist),且可以在单次遍历中完成分组,避免多次迭代带来的性能损耗。

如何按固定数量对列表进行分块?
按固定数量分块(Chunking)是最常见的分组场景之一。要实现这一点,你需要维护一个计数器,每取出指定数量的元素后,就创建一个新的 List 并将该组加入结果集。这种方法适用于需要将大数据集拆分为小批次处理的场景,例如批量数据库插入或分页显示。关键在于处理剩余不足一块数量的元素,确保它们也能被正确归入最后一组。

import java.util.*;
public class ChunkedIterator {
public static void main(String[] args) {
List<String> data = Arrays.asList("A", "B", "C", "D", "E");
int chunkSize = 2;
// 使用自定义方法实现分块
List<List<String>> chunks = chunkByIterator(data, chunkSize);
for (int i = 0; i < chunks.size(); i++) {
System.out.println("Chunk " + i + ": " + chunks.get(i));
}
}
public static List<List<String>> chunkByIterator(List<String> source, int size) {
List<List<String>> result = new ArrayList<>();
if (source == null || source.isEmpty()) return result;
Iterator<String> it = source.iterator();
while (it.hasNext()) {
List<String> chunk = new ArrayList<>();
for (int i = 0; i < size && it.hasNext(); i++) {
chunk.add(it.next());
}
result.add(chunk);
}
return result;
}
}
运行上述代码,输入为 [A, B, C, D, E] 且分块大小为 2,预期输出结果为:
Chunk 0: [A, B]
Chunk 1: [C, D]
Chunk 2: [E]
立即学习“Java免费学习笔记(深入)”;
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。
如何根据元素属性动态分组?
当需要根据元素的内在属性(如字符串长度、数值奇偶性等)进行分组时,可以在迭代过程中使用 Map 作为分组容器。每次调用 next() 获取元素后,计算其所属的组键(Key),如果 Map 中不存在该键,则新建一个 List 并放入 Map,然后将元素追加到该列表中。这种方式灵活性强,能够处理任意复杂的分组逻辑,且同样只需一次遍历即可完成所有分类。

import java.util.*;
public class DynamicGroupingIterator {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
// 按奇偶性分组
Map<String, List<Integer>> groups = groupByProperty(numbers);
System.out.println("Odd: " + groups.get("Odd"));
System.out.println("Even: " + groups.get("Even"));
}
public static Map<String, List<Integer>> groupByProperty(List<Integer> source) {
Map<String, List<Integer>> result = new HashMap<>();
Iterator<Integer> it = source.iterator();
while (it.hasNext()) {
Integer num = it.next();
String key = (num % 2 != 0) ? "Odd" : "Even";
result.computeIfAbsent(key, k -> new ArrayList<>()).add(num);
}
return result;
}
}
运行上述代码,输入为 [1, 2, 3, 4, 5, 6],预期输出结果为:
Odd: [1, 3, 5]
Even: [2, 4, 6]
迭代器遍历时移除元素会引发什么问题?
在使用 Iterator 进行分组或其他操作时,如果在循环内部直接调用集合对象的 remove() 方法,会抛出 ConcurrentModificationException。这是因为集合的内部修改计数器(modCount)与迭代器的预期值不一致。正确的做法是使用迭代器对象自身的 remove() 方法,该方法会在删除元素的同时同步更新迭代器和集合的状态,从而保证遍历的安全性。这在分组过程中若需要过滤掉某些元素时尤为重要。

















