File tree Expand file tree Collapse file tree 2 files changed +94
-0
lines changed Expand file tree Collapse file tree 2 files changed +94
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .winterbe .java8 ;
2
+
3
+ import java .util .Optional ;
4
+
5
+ /**
6
+ * @author Benjamin Winterberg
7
+ */
8
+ public class Streams6 {
9
+
10
+ static class Outer {
11
+ Nested nested ;
12
+ }
13
+
14
+ static class Nested {
15
+ Inner inner ;
16
+ }
17
+
18
+ static class Inner {
19
+ String foo ;
20
+ }
21
+
22
+ public static void main (String [] args ) {
23
+ test1 ();
24
+ }
25
+
26
+ private static void test1 () {
27
+ Optional .of (new Outer ())
28
+ .flatMap (o -> Optional .ofNullable (o .nested ))
29
+ .flatMap (n -> Optional .ofNullable (n .inner ))
30
+ .flatMap (i -> Optional .ofNullable (i .foo ))
31
+ .ifPresent (System .out ::print );
32
+ }
33
+ }
Original file line number Diff line number Diff line change
1
+ package com .winterbe .java8 ;
2
+
3
+ import java .util .ArrayList ;
4
+ import java .util .List ;
5
+ import java .util .stream .IntStream ;
6
+
7
+ /**
8
+ * @author Benjamin Winterberg
9
+ */
10
+ public class Streams7 {
11
+
12
+ static class Foo {
13
+ String name ;
14
+ List <Bar > bars = new ArrayList <>();
15
+
16
+ Foo (String name ) {
17
+ this .name = name ;
18
+ }
19
+ }
20
+
21
+ static class Bar {
22
+ String name ;
23
+
24
+ Bar (String name ) {
25
+ this .name = name ;
26
+ }
27
+ }
28
+
29
+ public static void main (String [] args ) {
30
+ // test1();
31
+ test2 ();
32
+ }
33
+
34
+ static void test2 () {
35
+ IntStream .range (1 , 4 )
36
+ .mapToObj (num -> new Foo ("Foo" + num ))
37
+ .peek (f -> IntStream .range (1 , 4 )
38
+ .mapToObj (num -> new Bar (f .name + " -> Bar" + num ))
39
+ .forEach (f .bars ::add ))
40
+ .flatMap (f -> f .bars .stream ())
41
+ .forEach (b -> System .out .println (b .name ));
42
+ }
43
+
44
+ static void test1 () {
45
+ List <Foo > foos = new ArrayList <>();
46
+
47
+ IntStream
48
+ .range (1 , 4 )
49
+ .forEach (num -> foos .add (new Foo ("Foo" + num )));
50
+
51
+ foos .forEach (f ->
52
+ IntStream
53
+ .range (1 , 4 )
54
+ .forEach (num -> f .bars .add (new Bar (f .name + " -> Bar" + num ))));
55
+
56
+ foos .stream ()
57
+ .flatMap (f -> f .bars .stream ())
58
+ .forEach (b -> System .out .println (b .name ));
59
+ }
60
+
61
+ }
You can’t perform that action at this time.
0 commit comments