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?
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());
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With