Develop code that uses the merge(), flatMap(), and map() methods on Java Streams
About the objectives of this section, only the merge
method has not yet been introduced in other sections.
-
You can put a new value on a map, or change the value that was already present using the
merge
method.src/org/j6toj8/collections/mergemap/Collections_Merge.javalink:../../../src/org/j6toj8/collections/mergemap/Collections_Merge.java[role=include]
console outputMap before merge: {1=String1-, 2=String2-} Map after merge: {1=String1-StringA, 2=String2-StringB, 3=StringC, 4=StringD}
Note that for keys that were already present in
Map
, the lambda function was applied. For keys that were not already present, only theString
passed as value was entered. -
You can transform values into a collection with the
map
method.src/org/j6toj8/collections/mergemap/Collections_Map.javalink:../../../src/org/j6toj8/collections/mergemap/Collections_Map.java[role=include]
console output2 4 6 8 10 12 14 16 18
-
You can traverse another Stream in sequence with the current Stream using the
flatMap
method.src/org/j6toj8/collections/mergemap/Collections_FlatMap.javalink:../../../src/org/j6toj8/collections/mergemap/Collections_FlatMap.java[role=include]
console outputWith map: java.util.stream.ReferencePipeline$Head@5f184fc6 With flatMap: M a n o e l
Note that a transformation that results in another Stream is traversed as if it were the original Stream itself.
-
Additions in Java 8
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 152). Wiley. Kindle Edition.
-
Using Streams
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Kindle Edition.