是否可以在 Java 中合并迭代器?

2022-01-10 00:00:00 iteration iterator java

是否可以在 Java 中合并迭代器?我有两个迭代器,我想组合/合并它们,以便我可以一次迭代它们的元素(在同一个循环中)而不是两个步骤.那可能吗?

Is it possible to merge iterators in Java? I have two iterators and I want to combine/merge them so that I could iterate though their elements in one go (in same loop) rather than two steps. Is that possible?

请注意,两个列表中的元素数量可能不同,因此对两个列表进行一次循环不是解决方案.

Note that the number of elements in the two lists can be different therefore one loop over both lists is not the solution.

Iterator<User> pUsers = userService.getPrimaryUsersInGroup(group.getId());
Iterator<User> sUsers = userService.getSecondaryUsersInGroup(group.getId());

while(pUsers.hasNext()) {
  User user = pUsers.next();
  .....
}

while(sUsers.hasNext()) {
  User user = sUsers.next();
  .....
}

推荐答案

Guava(原 Google Collections)有 Iterators.concat.

Guava (formerly Google Collections) has Iterators.concat.

相关文章