习惯用于通过排序集合的成对迭代 [英] Idiom for pairwise iteration through a sorted collection

查看:99
本文介绍了习惯用于通过排序集合的成对迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有Java成语通过排序 Collection 的元素进行成对迭代?我的意思是每个迭代可以访问集合的一个元素和集合的下一个元素?

Is there a Java idiom for pairwise iteration through the elements of a sorted Collection? By that I mean that each iteration has access to one element of the collection and the next element of the collection?

对于排序列表 s(和数组),可以使用索引到集合中来完成:

For sorted Lists (and arrays), it can be done using an index into the collection:

 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);
 }

但是 SortedSet ? ( SortedMap 可以使用 entrySet(),这相当于 SortedSet case)。

But what about SortedSet? (for SortedMap you can use its entrySet(), which is equivalent to the SortedSet case).

例如,如果您的排序集包含值{ 2,3,4},迭代将按顺序对于(1,2),(2,3),(3,4)。

So, for example, if your sorted set contained the values {1, 2, 3, 4}, the iterations would be for the pairs (1, 2), (2, 3), (3, 4), in that order.

推荐答案

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

You can simply implement it the following way (and apply similar strategy towards other collections):

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;
}

这篇关于习惯用于通过排序集合的成对迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆