Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over alternative elements using an iterator?

Tags:

java

iterator

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
Iterator<Integer> 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?

like image 888
Randhir Avatar asked May 14 '18 12:05

Randhir


2 Answers

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());
}
like image 120
daniu Avatar answered Sep 29 '22 19:09

daniu


You only want to print the odd numbers? Filter the list with a stream:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
Iterator<Integer> it = list.stream().filter(x -> x % 2 == 1).iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}

Edit:

if you want to get every other element then using streams will be less appropriate, but you can still do it:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
int limit = list.size() / 2 - (1 - list.size() % 2);
Iterator<Integer> it = IntStream.iterate(0, x -> x + 2).limit(limit).map(list::get).iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}

I recommend daniu's solution.

like image 42
Sweeper Avatar answered Sep 29 '22 21:09

Sweeper