Java flatMap

In this Java 8 tutorial you can learn about what a flatMap is and in which scenario it can be used. flatMap is an intermediate operation of the Java 8 Stream API. If you are just into Java 8 and streams, I strongly recommend you to go through the linked tutorial to learn about streams and operations.

Broadly stream operations are classified as intermediate and terminal operations. flatMap is an intermediate operation, which returns a new stream. Intermediate operations are classified as stateless and stateful operations based on need for sharing information between elements when processing them. flatMap is a stateless intermediate operation.

Java-flatMap

As per the Javadoc,

“…Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element…”

Following example will help you to understand this flatMap and a possible example scenario. Let us consider a zoo and the list of animals in it. Then we can use the flatMap to get an aggregate of animals in a list of Zoo. If we use the Pre-Java8 approach, we would be doing this by using multiple for-loops. Now the same can be achieve with Java 8 Stream API as below.

flatMap Example

package com.javapapers.java;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FlatMapExample {

	public static void main(String args[]) {
		List<Zoo> zooList = new ArrayList<>();
		Zoo nationalZoo = new Zoo("National");
		nationalZoo.add("Lion");
		nationalZoo.add("Tiger");
		nationalZoo.add("Peacock");
		nationalZoo.add("Gorilla");

		Zoo aCountyZoo = new Zoo("Wills County");
		aCountyZoo.add("Peacock");
		aCountyZoo.add("Camelion");

		zooList.add(nationalZoo);
		zooList.add(aCountyZoo);

		// to get the aggregate
		List<String> animalList = zooList.stream()
				.flatMap(element -> element.getAnimals().stream())
				.collect(Collectors.toList());
		System.out.println(animalList);

		// to get the unique set
		Set<String> animalSet = zooList.stream()
				.flatMap(element -> element.getAnimals().stream())
				.collect(Collectors.toSet());
		System.out.println(animalSet);

	}

}

class Zoo {
	private String zooName;
	private Set<String> animals;

	public Zoo(String zooName) {
		this.zooName = zooName;
		this.animals = new HashSet<>();
	}

	public void add(String animal) {
		this.animals.add(animal);
	}

	public Set<String> getAnimals() {
		return animals;
	}
}

Example Output

[Peacock, Lion, Tiger, Gorilla, Peacock, Camelion]
[Peacock, Lion, Tiger, Gorilla, Camelion]

Another year has passed and we are into a new year. Wishing you a happy new year and I wish you to achieve all your dreams.

For the regular reader of Java Papers, you might have noticed an unusual silence for the past two months. I am working on a project related to technology learning and it took all of my time. I will be launching it very soon to you and it will be maintained in-tandem with Java Papers. We have lot more coming up in Java Papers in 2016. My two resolutions for Java Papers are, as always continue to publish regularly and remove advertisements gradually from the blog. Keep reading, sharing and rocking!

This Java tutorial was added on 04/01/2016.

Comments on "Java flatMap" Tutorial:

  1. Swetja says:

    Happy new year Joe.

  2. Patrick says:

    So nice to hear about your resolutions for Java Papers. Keep flying!

  3. NAGENDRA says:

    Happy new year Joe.

  4. deepak says:

    If you will be removing the advertisement completely, then how you are gonna make this site working???

  5. Thiru says:

    HI Joe,

    I was reading your blog for than 4 years i think. Most of the time you have given an example of zoo.

    I wonder did you design the wonder zoo app game? Whenever i play this game you only come to my mind, the design patterns you explained in blog.

    Thanks,
    Thiru

  6. Joe says:

    @Thiru, So nice of you to drop a comment.

    Its just a habit. Zoo, animals and the surrounding theme is comfortable to represent OOPS and I needed something simpler. Nothing special, I just use it. :-)

Comments are closed for this "Java flatMap" tutorial.