-
Notifications
You must be signed in to change notification settings - Fork 81
/
IntersectionTypes.java
73 lines (59 loc) · 1.91 KB
/
IntersectionTypes.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
64
65
66
67
68
69
70
71
72
73
package dev.nipafx.demo.java10.lang.var;
import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import java.util.Optional;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class IntersectionTypes {
public static void main(String[] args) throws Exception {
boolean empty = ThreadLocalRandom.current().nextBoolean();
doItWithGenerics(empty);
doItWithVar(empty);
}
private static <T extends Closeable & Iterator<String>> void doItWithGenerics(boolean empty) throws IOException {
T elements = createCloseableIterator(empty);
Optional<String> dollarWord = firstMatch(elements, s -> s.startsWith("$"));
System.out.println(dollarWord.orElse("none"));
}
private static void doItWithVar(boolean empty) throws IOException {
var scanner = createCloseableIterator(empty);
Optional<String> dollarWord = firstMatch(scanner, s -> s.startsWith("$"));
System.out.println(dollarWord.orElse("none"));
}
@SuppressWarnings("unchecked")
private static <T extends Closeable & Iterator<String>> T createCloseableIterator(boolean empty) {
if (empty)
return (T) new Empty();
else
return (T) new Scanner(System.in);
}
private static <E, T extends Closeable & Iterator<E>> Optional<E> firstMatch(
T elements, Predicate<? super E> condition)
throws IOException {
try (elements) {
return stream(elements)
.filter(condition)
.findFirst();
}
}
private static <E> Stream<E> stream(Iterator<E> elements) {
return StreamSupport.stream(((Iterable<E>) () -> elements).spliterator(), false);
}
static class Empty<E> implements Closeable, Iterator<E> {
@Override
public void close() throws IOException {
}
@Override
public boolean hasNext() {
return false;
}
@Override
public E next() {
throw new IllegalStateException();
}
}
}