Idiom for pairwise iteration through a sorted collection

前端 未结 5 750
误落风尘
误落风尘 2021-01-03 02:54

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 co

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 03:27

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

    Iterator iter = set.iterator();
    Thing previous = iter.hasNext() ? iter.next() : null;
    while (iter.hasNext()) {
        final Thing current = iter.next();
        operateOnAdjacentPair(previous, current);
        previous = current;
    }
    

提交回复
热议问题