Skip to content

Latest commit

 

History

History
92 lines (79 loc) · 2.26 KB

File metadata and controls

92 lines (79 loc) · 2.26 KB

Maps and Streams

Objective
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.

  1. 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.java
    link:../../../src/org/j6toj8/collections/mergemap/Collections_Merge.java[role=include]
    console output
    Map 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 the String passed as value was entered.

  2. You can transform values into a collection with the map method.

    src/org/j6toj8/collections/mergemap/Collections_Map.java
    link:../../../src/org/j6toj8/collections/mergemap/Collections_Map.java[role=include]
    console output
    2
    4
    6
    8
    10
    12
    14
    16
    18
  3. You can traverse another Stream in sequence with the current Stream using the flatMap method.

    src/org/j6toj8/collections/mergemap/Collections_FlatMap.java
    link:../../../src/org/j6toj8/collections/mergemap/Collections_FlatMap.java[role=include]
    console output
     With 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.

References
  • 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.

  • The Java 8 Stream API Tutorial.

  • Merging Two Maps with Java 8.