-
Notifications
You must be signed in to change notification settings - Fork 112
/
Solution.java
61 lines (48 loc) · 1.43 KB
/
Solution.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
57
58
59
60
61
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* @author Oleg Cherednik
* @since 14.02.2019
*/
public class Solution {
public static void main(String... args) {
List<String> words = Arrays.asList("one", "two", "three", "four", "five");
PeekableInterface<String> it = new PeekableInterface<>(words);
int i = 0;
while (it.hasNext()) {
if (i++ % 2 == 0)
System.out.format("next:%s -> peek:%s\n", it.next(), it.hasNext() ? it.peek() : null);
else
System.out.format("peek:%s -> next:%s\n", it.peek(), it.next());
}
}
public static final class PeekableInterface<E> implements Iterator<E> {
private final Iterator<E> it;
private E next;
private boolean nextExists;
public PeekableInterface(Iterable<E> iterable) {
it = iterable.iterator();
}
@Override
public boolean hasNext() {
return nextExists || it.hasNext();
}
@Override
public E next() {
if (nextExists) {
E e = next;
nextExists = false;
next = null;
return e;
}
return it.next();
}
public E peek() {
if (!nextExists)
next = it.next();
nextExists = true;
return next;
}
}
}