Skip to content

Commit a348200

Browse files
committed
Add more stream examples
1 parent c8d5204 commit a348200

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

src/com/winterbe/java8/Streams6.java

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package com.winterbe.java8;
2+
3+
import java.io.IOException;
4+
import java.math.BigDecimal;
5+
import java.nio.file.Files;
6+
import java.nio.file.Path;
7+
import java.nio.file.Paths;
8+
import java.util.Arrays;
9+
import java.util.stream.IntStream;
10+
import java.util.stream.Stream;
11+
12+
/**
13+
* @author Benjamin Winterberg
14+
*/
15+
public class Streams6 {
16+
17+
public static void main(String[] args) throws IOException {
18+
// test1();
19+
// test2();
20+
// test3();
21+
// test4();
22+
// test5();
23+
// test6();
24+
// test7();
25+
test8();
26+
}
27+
28+
private static void test8() throws IOException {
29+
Path start = Paths.get("/Users/benny/Documents");
30+
int maxDepth = 5;
31+
long fileCount =
32+
Files
33+
.walk(start, maxDepth)
34+
.filter(path -> String.valueOf(path).endsWith("xls"))
35+
.count();
36+
System.out.format("XLS files found: %s", fileCount);
37+
}
38+
39+
private static void test7() throws IOException {
40+
Path start = Paths.get("/Users/benny/Documents");
41+
int maxDepth = 5;
42+
Files
43+
.find(start, maxDepth, (path, attr) ->
44+
String.valueOf(path).endsWith("xls"))
45+
.sorted()
46+
.forEach(System.out::println);
47+
}
48+
49+
private static void test6() throws IOException {
50+
Files
51+
.list(Paths.get("/usr"))
52+
.sorted()
53+
.forEach(System.out::println);
54+
}
55+
56+
private static void test5() throws IOException {
57+
Files
58+
.lines(Paths.get("/foo", "bar"))
59+
.filter(line -> line.startsWith("A"))
60+
.forEach(System.out::println);
61+
}
62+
63+
private static void test4() {
64+
Stream
65+
.of(new BigDecimal("1.2"), new BigDecimal("3.7"))
66+
.mapToDouble(BigDecimal::doubleValue)
67+
.average()
68+
.ifPresent(System.out::println);
69+
}
70+
71+
private static void test3() {
72+
IntStream
73+
.range(0, 10)
74+
.average()
75+
.ifPresent(System.out::println);
76+
}
77+
78+
private static void test2() {
79+
IntStream
80+
.builder()
81+
.add(1)
82+
.add(3)
83+
.add(5)
84+
.add(7)
85+
.add(11)
86+
.build()
87+
.average()
88+
.ifPresent(System.out::println);
89+
90+
}
91+
92+
private static void test1() {
93+
int[] ints = {1, 3, 5, 7, 11};
94+
Arrays
95+
.stream(ints)
96+
.average()
97+
.ifPresent(System.out::println);
98+
}
99+
}

0 commit comments

Comments
 (0)