How to iterate over alternative elements using an iterator

  • A+
Category:Languages
List<Integer> list = Arrays.asList(1,2,3,4,5,6); Iterator it = list.iterator(); while(it.hasNext()){     System.out.println(it.next()); } 

The above code will iterate sequentially 1 through 6. Can we iterate the same list alternatively so that it will print 1,3,5 without changing the while loop?


Create your own Iterator.

class SkippingIterator<T> implements Iterator<T> {     private List<T> list;     private currentPosition;     private int skipBy;     public SkippingIterator(List<T> l) {         this(l, 2);     }     public SkippingIterator(List<T> l, int skip) {         this(l, skipBy, 0);     }     public SkippingIterator(List<T> l, int skip, int startPosition) {         list = l;         skipBy = skip;         currentPosition = startPosition;     }     public boolean hasNext() {         return currentPosition < list.size();     }     public T next() {         T result = list.get(currentPosition);         currentPosition += skip;         return result;     } } 

making your code

List<Integer> list = Arrays.asList(1,2,3,4,5,6); Iterator it = new SkippingIterator<>(list); while(it.hasNext()){     System.out.println(it.next()); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: