|
| 1 | +package com.winterbe.java11; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileOutputStream; |
| 5 | +import java.io.IOException; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Optional; |
| 9 | +import java.util.stream.Collectors; |
| 10 | +import java.util.stream.Stream; |
| 11 | + |
| 12 | +public class Misc { |
| 13 | + |
| 14 | + @Deprecated(forRemoval = true) |
| 15 | + String foo; |
| 16 | + |
| 17 | + public static void main(String[] args) throws IOException { |
| 18 | + collections(); |
| 19 | + strings(); |
| 20 | + optionals(); |
| 21 | + inputStreams(); |
| 22 | + streams(); |
| 23 | + } |
| 24 | + |
| 25 | + private static void streams() { |
| 26 | + System.out.println(Stream.ofNullable(null).count()); // 0 |
| 27 | + System.out.println(Stream.of(1, 2, 3, 2, 1) |
| 28 | + .dropWhile(n -> n < 3) |
| 29 | + .collect(Collectors.toList())); // [3, 2, 1] |
| 30 | + System.out.println(Stream.of(1, 2, 3, 2, 1) |
| 31 | + .takeWhile(n -> n < 3) |
| 32 | + .collect(Collectors.toList())); // [1, 2] |
| 33 | + } |
| 34 | + |
| 35 | + private static void inputStreams() throws IOException { |
| 36 | + var classLoader = ClassLoader.getSystemClassLoader(); |
| 37 | + var inputStream = classLoader.getResourceAsStream("com/winterbe/java11/dummy.txt"); |
| 38 | + var tempFile = File.createTempFile("dummy-copy", "txt"); |
| 39 | + try (var outputStream = new FileOutputStream(tempFile)) { |
| 40 | + inputStream.transferTo(outputStream); |
| 41 | + } |
| 42 | + System.out.println(tempFile.length()); |
| 43 | + } |
| 44 | + |
| 45 | + private static void optionals() { |
| 46 | + System.out.println(Optional.of("foo").orElseThrow()); // foo |
| 47 | + System.out.println(Optional.ofNullable(null).or(() -> Optional.of("bar")).get()); // bar |
| 48 | + System.out.println(Optional.of("foo").stream().count()); // 1 |
| 49 | + } |
| 50 | + |
| 51 | + private static void strings() { |
| 52 | + System.out.println(" ".isBlank()); |
| 53 | + System.out.println(" Foo Bar ".strip()); // "Foo Bar" |
| 54 | + System.out.println(" Foo Bar ".stripTrailing()); // " Foo Bar" |
| 55 | + System.out.println(" Foo Bar ".stripLeading()); // "Foo Bar " |
| 56 | + System.out.println("Java".repeat(3)); // "JavaJavaJava" |
| 57 | + System.out.println("A\nB\nC".lines().count()); // 3 |
| 58 | + } |
| 59 | + |
| 60 | + private static void collections() { |
| 61 | + var list = List.of("A", "B", "C"); |
| 62 | + var copy = List.copyOf(list); |
| 63 | + System.out.println(list == copy); // true |
| 64 | + |
| 65 | + var map = Map.of("A", 1, "B", 2); |
| 66 | + System.out.println(map); |
| 67 | + } |
| 68 | + |
| 69 | +} |
0 commit comments