Skip to content

Unraveling the Magic of 'Streams.of' and 'flatMap' in Functional Programming

Posted on:August 31, 2023 at 01:13 PM

Hello, coding sisters! Welcome back to yet another captivating chapter of our journey through the enchanting realm of functional programming. As we dive deeper into the seas of code, let’s explore two fascinating concepts that will elevate your mastery of streams: the enigmatic Streams.of method and the transformative power of flatMap. Brace yourselves, for we are about to unravel these intriguing concepts and witness their wondrous applications in the world of Java streams.

Table of contents

Open Table of contents

Sections

Embarking on the Journey: Introducing ‘Streams.of’

Our journey begins with a simple question: can we create a stream from existing streams? Imagine having two separate streams – stream A containing elements “hello” and “there,” and stream B with elements “learning” and “java.” Could we invoke the Streams.of method on these streams to create a new stream C? The answer, unfortunately, is not that simple. When we attempt to use Streams.of(a, b), we encounter an error. Why? Because what we end up with is not a stream of elements but a stream of streams. Intriguing, isn’t it?

Unleashing the Flattening Magic: Introducing ‘flatMap’

Fear not, for there’s a solution that lies within the mystical realm of flatMap. This method comes to our aid when we need to flatten a stream of streams into a single stream. Allow us to illustrate the incantations:

Stream<String> streamA = Stream.of("hello", "there");
Stream<String> streamB = Stream.of("learning", "java");
Stream<Stream<String>> streamC = Stream.of(streamA, streamB);

Stream<String> flattenedStream = streamC.flatMap(identityFunction);

1 - Gathering Streams: We begin by creating stream A and stream B, each with its own set of elements. Then, we attempt to create a stream C containing these two streams.

2 - Enter flatMap: Alas, the elusive Streams.of method does not provide the desired result. But behold! The flatMap method emerges as our savior. It takes a mapper function – in this case, an identity function that returns the same element.

3 - Magical Transformation: As we invoke flatMap, a mesmerizing transformation unfolds. Each element within stream C, which represents streams A and B, undergoes the spell of the identity function. This incantation breaks down the nested streams into their individual elements, revealing the true power of flattening.

Understanding the Essence of flatMap

At its core, flatMap takes a function that returns a stream. Unlike the map operation, where the mapper function can return any value, flatMap is bound to return a stream. While the generic syntax might seem intricate, mastering the timing and use of flatMap is a skill that will prove invaluable in your coding endeavors.

A Real-Life Enchantment: Reading Words from a Text File

Path filePath = Paths.get("path/to/your/text/file.txt");

try (Stream<String> lines = Files.lines(filePath)) {
    List<String> allWords = lines
        .flatMap(line -> Arrays.stream(line.split(" ")))
        .collect(Collectors.toList());

    allWords.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

1- Enchanting the File Path: We begin by specifying the path to our text file, a treasure trove of words waiting to be discovered.

2- Reading Lines: Through the incantations of the Files.lines method, we conjure a stream of lines from the text file.

3- The flatMap Ritual: Here comes the heart of the enchantment. The flatMap spell is cast upon each line, breaking it into individual words. This creates a new stream containing all the words.

4- Collecting the Words: The stream of words is then collected into a list, ready for your beck and call.

5- Revelation of Words: As we traverse the list, the words reveal themselves, each unique and intriguing.

The Path Ahead

And there you have it, valiant coders! The mysterious Streams.of method and the transformative power of flatMap are now within your grasp. With flatMap, you hold the key to unraveling nested streams, flattening them into a seamless cascade of elements. Whether you’re summoning streams from streams or conjuring words from text files, flatMap is your trusty wand in the realm of functional programming.

You can find the repo for this section of the course Here