【问题标题】:Getting the current and the next element from a collection in a loop, using Iterator, in Java在Java中使用迭代器从循环中的集合中获取当前元素和下一个元素
【发布时间】:2018-03-02 21:03:37
【问题描述】:

我有一个Collection<T>,名为“col”。包含类 T 的内容并不重要。当我迭代集合时,在每次迭代时,我都需要拥有当前元素和下一个元素。

Iterator it = col.iterator();
while (it.hasNext()) {
  T line = (T) it.next();
  T nextLine = it.hasNext()? NEXT_LINE : null;
  // more Java code with line and nextLine
}

“NEXT_LINE”不是一个声明的常量,而是一个无效的代码。我需要用一个有效的 Java 代码替换它,该代码返回集合中的下一个元素,而无需再次递增迭代器。

我找到了这个链接: Java iterator get next without incrementing

在我的例子中,这个解决方案的弱点是如果集合只包含 1 个元素,我必须在我的代码中做太多的更改。如果我的版本有解决方案,则覆盖 1 个元素的情况,因为 nextLine 为空。

我也可以将集合转换为 ArrayList,但只有在我认为没有更好的方法时才会这样做:

ArrayList<T> list = new ArrayList<T>(col);
for (int i=0; i<list.size(); i++) {
  T line = list.get(i);
  T nextLine = i<list.size()-1 ? list.get(i+1) : null;
  // more Java code with line and nextLine
}

【问题讨论】:

  • 链表听起来更适合这里

标签: java collections iterator next


【解决方案1】:

Guava 包含PeekingIterator 接口,这可能是您的解决方案。

PeekingIterator it = Iterators.peekingIterator(col.iterator());
while (it.hasNext()) {
    T line = (T) it.next();
    T nextLine = it.hasNext()? it.peek() : null;
}

更多信息here。看起来很符合你现在的结构。

【讨论】:

    【解决方案2】:

    Iterator的用法如下(1个it.hasNext()和1个it.next())。

    Iterator<T> it = col.iterator();
    T previous = null;
    if (it.hasNext()) {
        previous = it.next();
        while (it.hasNext()) {
          T next = it.next();
          // ... previous ... next ..
          previous = next;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-05
      • 2018-04-13
      • 2011-07-03
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      相关资源
      最近更新 更多