Idiom for pairwise iteration through a sorted collection

前端 未结 5 755
误落风尘
误落风尘 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:20

    Write an implementation of Iterator, e.g. (just writing off the top of my head, so code may not work as is)

    public class PairwiseIterator implements Iterator> {
        private final Iterator elements;
        private T last;
    
        public PairwiseIterator(Collection elements) {
            this.elements = elements.iterator();
            last = elements.hasNext() ? elements.next() : null;
        }
    
        @Override
        public boolean hasNext() {
            return elements.hasNext();
        }
    
        @Override
        public List next() {
            List result = ImmutableList.of(last, elements.next());
            last = result.get(1);
            return result;
        }
    
        @Override
        public void remove() {
            throw new UnsupportedOperationException("Remove not allowed with this iterator");
        }
    
        public static  Iterable> iterable(final Collection elements) {
            return new Iterable() {
                public Iterator iterator() {
                    return new PairwiseIterator(elements);
                }
            }
        }
    }
    

    I probably don't have the types exactly right, but the 'iterable' method makes it easy to use in foreach constructs:

    for(List pair : PairwiseIterator.iterable(orderedSetOfStrings)) {
        // ... do what you need to ...
    }
    

提交回复
热议问题