-
Notifications
You must be signed in to change notification settings - Fork 17
/
EvenIterator.java
56 lines (47 loc) · 1.32 KB
/
EvenIterator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package by.andd3dfx.iterators;
import lombok.RequiredArgsConstructor;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Build iterator which returns only even numbers of underlying array:
* [1, 3, 5, 7, 8, 9] -> [8]
*
* @see <a href="https://youtu.be/wY5Hg3KrLqw">Video solution</a>
*/
@RequiredArgsConstructor
public class EvenIterator implements Iterator<Integer> {
private final Iterator<Integer> it;
private Deque<Integer> stack = new ArrayDeque<>();
@Override
public Integer next() {
if (!stack.isEmpty()) {
return stack.pop();
}
while (it.hasNext()) {
Integer value = it.next();
if (value % 2 == 0) {
return value;
}
}
throw new NoSuchElementException("Iterator is empty!");
}
@Override
public boolean hasNext() {
if (!stack.isEmpty()) {
return true;
}
while (it.hasNext()) {
var value = it.next();
if (value % 2 == 0) {
stack.push(value);
break;
}
}
if (stack.isEmpty()) {
return it.hasNext();
}
return true;
}
}