gpt4 book ai didi

java - 在 Java 中使用迭代器从循环中的集合中获取当前元素和下一个元素

转载 作者:行者123 更新时间:2023-11-29 08:33:04 24 4
gpt4 key购买 nike

我有一个 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
}

最佳答案

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

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

更多信息 here .似乎很符合您当前的结构。

关于java - 在 Java 中使用迭代器从循环中的集合中获取当前元素和下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46345139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com