forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMisc.java
More file actions
69 lines (58 loc) · 2.3 KB
/
Misc.java
File metadata and controls
69 lines (58 loc) · 2.3 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.winterbe.java11;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Misc {
@Deprecated(forRemoval = true)
String foo;
public static void main(String[] args) throws IOException {
collections();
strings();
optionals();
inputStreams();
streams();
}
private static void streams() {
System.out.println(Stream.ofNullable(null).count()); // 0
System.out.println(Stream.of(1, 2, 3, 2, 1)
.dropWhile(n -> n < 3)
.collect(Collectors.toList())); // [3, 2, 1]
System.out.println(Stream.of(1, 2, 3, 2, 1)
.takeWhile(n -> n < 3)
.collect(Collectors.toList())); // [1, 2]
}
private static void inputStreams() throws IOException {
var classLoader = ClassLoader.getSystemClassLoader();
var inputStream = classLoader.getResourceAsStream("com/winterbe/java11/dummy.txt");
var tempFile = File.createTempFile("dummy-copy", "txt");
try (var outputStream = new FileOutputStream(tempFile)) {
inputStream.transferTo(outputStream);
}
System.out.println(tempFile.length());
}
private static void optionals() {
System.out.println(Optional.of("foo").orElseThrow()); // foo
System.out.println(Optional.ofNullable(null).or(() -> Optional.of("bar")).get()); // bar
System.out.println(Optional.of("foo").stream().count()); // 1
}
private static void strings() {
System.out.println(" ".isBlank());
System.out.println(" Foo Bar ".strip()); // "Foo Bar"
System.out.println(" Foo Bar ".stripTrailing()); // " Foo Bar"
System.out.println(" Foo Bar ".stripLeading()); // "Foo Bar "
System.out.println("Java".repeat(3)); // "JavaJavaJava"
System.out.println("A\nB\nC".lines().count()); // 3
}
private static void collections() {
var list = List.of("A", "B", "C");
var copy = List.copyOf(list);
System.out.println(list == copy); // true
var map = Map.of("A", 1, "B", 2);
System.out.println(map);
}
}