-
Notifications
You must be signed in to change notification settings - Fork 1
/
Iterators.java
63 lines (52 loc) · 1.58 KB
/
Iterators.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
62
63
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
/**
* @author Alessandro Lombardini
*/
public final class Iterators {
private Iterators(){}
public static<T> Iterator<T> concat(Iterator<T> it1, Iterator<T> it2){
return new Iterator<T>() {
boolean switched = false;
Iterator<T> it = it1;
@Override
public boolean hasNext () {
return it.hasNext();
}
@Override
public T next () {
if(!switched)
if(!hasNext()){
it = it2;
switched = true;
}
if(it.hasNext()) return it.next();
throw new UnsupportedOperationException();
}
};
}
public static <T,R> Iterator<R> map(Iterator<T> it, Function<T,R> fnc){
return new Iterator<>() {
@Override
public boolean hasNext () {
return it.hasNext();
}
@Override
public R next () {
if(it.hasNext())
return fnc.apply(it.next());
throw new UnsupportedOperationException();
}
};
}
static <T extends Comparable<T>> T max(Iterator<T> it){
if(!it.hasNext()) throw new NoSuchElementException();
T max = it.next();
while (it.hasNext()){
T next = it.next();
if(max.compareTo(next) < 0) max = next;
}
return max;
}
}