-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample143.java
More file actions
49 lines (43 loc) · 1.36 KB
/
Example143.java
File metadata and controls
49 lines (43 loc) · 1.36 KB
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
// Example 143 from page 113
//
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.IntUnaryOperator;
import java.util.stream.IntStream;
class Example143 {
public static void main(String[] args) {
for (int i : fromTo(13, 17))
System.out.println(i);
for (int i : fromToStream(13, 17))
System.out.println(i);
List<IntUnaryOperator> functions = new ArrayList<>();
for (int i : fromTo(13, 17))
functions.add(j -> j * i);
for (IntUnaryOperator f : functions)
System.out.println(f.applyAsInt(10));
}
public static Iterable<Integer> fromTo(final int m, final int n) {
class FromToIterator implements Iterator<Integer> {
private int i = m;
public boolean hasNext() { return i <= n; }
public Integer next() {
if (i <= n)
return i++;
else
throw new NoSuchElementException();
}
public void remove() { throw new UnsupportedOperationException(); }
}
class FromToIterable implements Iterable<Integer> {
public Iterator<Integer> iterator() {
return new FromToIterator();
}
}
return new FromToIterable();
}
public static Iterable<Integer> fromToStream(final int m, final int n) {
return () -> IntStream.rangeClosed(m, n).iterator();
}
}