Idiom for pairwise iteration through a sorted collection

前端 未结 5 751
误落风尘
误落风尘 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条回答
  •  自闭症患者
    2021-01-03 03:12

    For Sets (and other non-indexable collections) you will need to use their Iterators as returned by the iterator() method of Collection:

    Iterator iter = set.iterator();
    Thing thing1 = iter.next();  // might want to check if this exists
    while (iter.hasNext()) {
        Thing thing2 = iter.next();
        operateOnAdjacentPair(thing1, thing2);
        thing1 = thing2;
    }
    

    You can do the same for Maps, using the Iterator of their entrySet()s.


    Now that I understand your question better, you could also try this:

    Iterator iter1 = set.iterator(), iter2 = set.iterator();
    
    if (iter2.hasNext())
        iter2.next();  // burn first element
    
    while (iter2.hasNext()) {
        final Thing thing1 = iter1.next();
        final Thing thing2 = iter2.next();
        operateOnAdjacentPair(thing1, thing2);
    }
    

提交回复
热议问题