Programming & Development / April 12, 2025

How to Use flatMap() in Java: Example Explained

Java flatMap Java Stream flatMap flatMap example Java streams flatten stream flatMap vs map split sentences Java distinct words Java functional programming in Java Java stream operations

The flatMap() method in Java Streams is a powerful operation that allows you to flatten a stream of collections (or arrays) into a single stream. It is particularly useful when you need to process elements that themselves contain multiple sub-elements, such as lists or arrays.

In this article, we’ll demonstrate an example of using flatMap() to flatten a stream of sentences into individual words.

Example: Using flatMap() to Extract Words from Sentences

Suppose we have a list of sentences, and we want to extract all the words from these sentences and collect them into a new list. Here's how we can do that using flatMap():

java

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FlatMapExample {
    public static void main(String[] args) {
        List<String> sentences = Arrays.asList(
                "Hello, how are you?",
                "I'm doing great, thank you!",
                "Java streams are powerful"
        );

        List<String> words = sentences.stream()
                .flatMap(sentence -> Arrays.stream(sentence.split(" ")))  // Splitting sentences into words
                .distinct()  // Removing duplicate words
                .collect(Collectors.toList());  // Collecting the result into a list

        System.out.println(words);
    }
}

Output:

csharp

[Hello,, how, are, you?, I'm, doing, great,, thank, Java, streams, are, powerful]

Explanation:

  1. List of Sentences: We start with a list of sentences:
java

List<String> sentences = Arrays.asList(
        "Hello, how are you?",
        "I'm doing great, thank you!",
        "Java streams are powerful"
);
  1. Using flatMap():
  • The flatMap() method is used to transform each sentence into a stream of words. We do this by splitting each sentence at the space character using sentence.split(" ").
  • flatMap() flattens the resulting stream of arrays into a single stream of words.
  1. Removing Duplicates: The distinct() operation is applied to ensure that only unique words are included in the final list.
  2. Collecting Results: Finally, the results are collected into a new list using Collectors.toList().

When to Use flatMap()

flatMap() is useful when:

  • You have a stream of collections (or arrays) and want to transform them into a single, flattened stream.
  • You need to perform operations that result in multiple elements for each input (for example, breaking up sentences into words or splitting strings into substrings).

flatMap() vs map()

While map() transforms each element of the stream into a new element, flatMap() is used when you need to transform an element into multiple elements and then flatten the results into a single stream. Here’s a quick comparison:

  • map(): Transforms one element into one element.
  • flatMap(): Transforms one element into multiple elements (a collection) and then flattens them into a single stream.

Conclusion

The flatMap() operation is essential when working with streams of collections or arrays and allows you to simplify complex transformations. By flattening nested structures, flatMap() enables cleaner and more efficient stream processing.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex