通过排序集合成对迭代的成语

Rae*_*ald 5 java collections

是否存在用于通过排序元素的成对迭代的Java习惯用法Collection?我的意思是每次迭代都可以访问集合的一个元素和集合的下一个元素?

对于排序的Lists(和数组),可以使用集合中的索引来完成:

 final int n = list.size();
 assert 2 <= n;
 for (int i = 0; i < n - 1; ++i) {
    final Thing thing1 = list.get(i);
    final Thing thing2 = list.get(i+1);
    operateOnAdjacentPair(thing1, thing2);
 }
Run Code Online (Sandbox Code Playgroud)

但那怎么样SortedSet?(因为SortedMap你可以使用它entrySet(),这相当于SortedSet案例).


因此,例如,如果您的有序集包含值{1,2,3,4},则迭代将按对象(1,2),(2,3),(3,4)的顺序进行.

Bri*_*ham 5

Iterator<Thing> thingerator = coll.iterator();
if (thingerator.hasNext()) {
    Thing thing1 = thingerator.next();
    while (thingerator.hasNext()) {
      final Thing thing2 = thingerator.next();
      doStuffToThings(thing1, thing2);

      thing1 = thing2;
    }
}
Run Code Online (Sandbox Code Playgroud)


Jyr*_*117 3

您可以简单地通过以下方式实现它(并对其他集合应用类似的策略):

Iterator<Thing> iter = set.iterator();
Thing previous = iter.hasNext() ? iter.next() : null;
while (iter.hasNext()) {
    final Thing current = iter.next();
    operateOnAdjacentPair(previous, current);
    previous = current;
}
Run Code Online (Sandbox Code Playgroud)