|
| 1 | +package org.codefx.demo.java10.lang.var; |
| 2 | + |
| 3 | +import java.io.Closeable; |
| 4 | +import java.io.IOException; |
| 5 | +import java.util.Iterator; |
| 6 | +import java.util.Optional; |
| 7 | +import java.util.Random; |
| 8 | +import java.util.Scanner; |
| 9 | +import java.util.function.Predicate; |
| 10 | +import java.util.stream.Stream; |
| 11 | +import java.util.stream.StreamSupport; |
| 12 | + |
| 13 | +import static java.util.stream.StreamSupport.stream; |
| 14 | + |
| 15 | +public class IntersectionTypes { |
| 16 | + |
| 17 | + public static void main(String[] args) throws Exception { |
| 18 | + boolean empty = new Random().nextBoolean(); |
| 19 | + doItWithGenerics(empty); |
| 20 | + doItWithVar(empty); |
| 21 | + } |
| 22 | + |
| 23 | + private static <T extends Closeable & Iterator<String>> void doItWithGenerics(boolean empty) throws IOException { |
| 24 | + T elements = createCloseableIterator(empty); |
| 25 | + Optional<String> dollarWord = firstMatch(elements, s -> s.startsWith("$")); |
| 26 | + System.out.println(dollarWord.orElse("none")); |
| 27 | + } |
| 28 | + |
| 29 | + private static void doItWithVar(boolean empty) throws IOException { |
| 30 | + var scanner = createCloseableIterator(empty); |
| 31 | + Optional<String> dollarWord = firstMatch(scanner, s -> s.startsWith("$")); |
| 32 | + System.out.println(dollarWord.orElse("none")); |
| 33 | + } |
| 34 | + |
| 35 | + @SuppressWarnings("unchecked") |
| 36 | + private static <T extends Closeable & Iterator<String>> T createCloseableIterator(boolean empty) { |
| 37 | + if (empty) |
| 38 | + return (T) new Empty(); |
| 39 | + else |
| 40 | + return (T) new Scanner(System.in); |
| 41 | + } |
| 42 | + |
| 43 | + private static <E, T extends Closeable & Iterator<E>> Optional<E> firstMatch( |
| 44 | + T elements, Predicate<? super E> condition) |
| 45 | + throws IOException { |
| 46 | + try (elements) { |
| 47 | + return stream(elements) |
| 48 | + .filter(condition) |
| 49 | + .findAny(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + private static <E> Stream<E> stream(Iterator<E> elements) { |
| 54 | + return StreamSupport.stream(((Iterable<E>) () -> elements).spliterator(), false); |
| 55 | + } |
| 56 | + |
| 57 | + static class Empty<E> implements Closeable, Iterator<E> { |
| 58 | + |
| 59 | + @Override |
| 60 | + public void close() throws IOException { |
| 61 | + |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + public boolean hasNext() { |
| 66 | + return false; |
| 67 | + } |
| 68 | + |
| 69 | + @Override |
| 70 | + public E next() { |
| 71 | + return null; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | +} |
0 commit comments