Wednesday 6 March 2024

Differences between map() and flatMap() stream operations in Java

Let’s explore the differences between map() and flatMap() stream operations in Java, along with examples: 

  1. map(): 

    • Role: The map() operation is used to transform each element of a stream into another object using a given function. 

    • Functionality: 

      • Produces one output for each input value. 

      • Maintains the same order as the original stream. 

      • Transformation is one-to-one. 

    • Example: 

        List<String> listOfStrings = Arrays.asList("1", "2", "3", "4", "5"); 

        List<Integer> listOfIntegers = listOfStrings.stream() 

        .map(Integer::valueOf) 

        .toList(); 

        // Output: [1, 2, 3, 4, 5] 


flatMap():

        Role: The flatMap() operation is used when each element in the stream is transformed into multiple elements, often in the form of another collection or stream. 

      Functionality: 

    • Produces arbitrary number of values for each input. 

    • Flattens the resulting elements into a single stream. 

    • Transformation is one-to-many (map() + flattening).  

       Example:

                    List<List<Integer>> listOfLists = Arrays.asList( 

                    Arrays.asList(1, 2, 3), 

                    Arrays.asList(4, 5), 

                    Arrays.asList(6, 7, 8) 

                ); 

                    List<Integer> flattenedList = listOfLists.stream() 

                    .flatMap(list -> list.stream()) 

                    .toList(); 

                    // Output: [1, 2, 3, 4, 5, 6, 7, 8] 



keep Learning Keep Coding......