Java 8 map and flatMap

In this post, we will be taking a look at the map and flatMap methods introduced in Java 8. We will be looking at a scenario where the map method does not produce the required output and why we really need the flatMap method. I will be using multiple examples to illustrate the same and also show you imperative and declarative styles of coding.

map: Let us consider the scenario where we have a collection of Person objects. Given a list of person objects, what if we wanted to return only the names of the people who have UK citizenship.

The imperative style of writing code would give us the following:


public List<String> getNamesOfUKCitizens(List<Person> persons)
{
List<String> allUKCitizens = new ArrayList<>();
for(Person p : persons)
{
if(p.getCitizenship() == Citizenship.UK){
allUKCitizens.add(p.getName());
}
}
return allUKCitizens;
}

To get this, we have to initialize an empty list, iterate through the loop, filter the people who have UK citizenship and then add the names to the empty list we create.Let’s try and solve this the  declarative way, using the map method.

The map method basically takes an object of one type and gives us an object of another type.


public List<String> getNamesOfUKCitizens()
{
return persons.stream()
.filter( p -> p.getCitizenship() == Citizenship.UK)
.map(p -> p.getName())
.collect(Collectors.toList());
}

Map_Flatmap_Pic1
filter,map and collect – Once the knob is turned on, everything happens !

The signature of the map method:

<R> Stream<R> map(Function<? super T,? extends R> mapper)

The signature looks complicated but it is easy to understand. The R is the output type of the stream and T is the input type.

Remember how the filter method (explained here) took a Predicate as a parameter? The map method takes a Function. This is also a functional interface. The function gets applied to each element. The p -> p.getName is a lambda expression, the function that gets applied to the Person object.  To understand this better, we could write the same thing as follows:


public List<String> getNamesOfUKCitizens()
{
Function<Person,String> mapper = p -> p.getName();
return persons.stream()
.filter( p -> p.getCitizenship() == Citizenship.UK)
.map(mapper)
.collect(Collectors.toList());
}

Remember that the map method takes one object and returns exactly one object. This is 1-1.

Few more examples of map API:

1.Given a list of numbers, we want to generate the square of each number:

We have input as a list of numbers of 1 type and we want to transform it:

Input: List<Integer> numbers = Arrays.asList(1,2,3,4,5);


numbers.stream()
.map( number -> number * 2)
.collect(Collectors.toList());

 Output:

[2, 4, 6, 8, 10]

2. Given a list of string, convert each string to upper case:

Transformation of one type to another, this time String to String – use map function

Input:

List<String> strings = Arrays.asList(“abc”,”pqr”,”xyz”);


strings.stream()
.map(s -> s.toUpperCase())
.collect(Collectors.toList()));

Output:  [ABC, PQR, XYZ]

3.Given a list of string, find the length of each string:

Input:

List<String> strings = Arrays.asList(“abc”,”pqr”,”xyz”);

Input to the map is a string and output is the length of each string.


strings.stream()
.map(s -> s.length())
.collect(Collectors.toList()));

Output: [3, 3, 3]

FlatMap: To understand the flatMap, let us consider a different example. Let us consider there are 3 systems and each system returns a list of strings. There is an application which combines these lists and sends the data back to us. Our system needs to take this input and generate all the strings as a single output.

List<String> system1 = Arrays.asList(“AB”,”cd”,”EF”);

List<String> system2 = Arrays.asList(“GH”,”ij”);

List<String> system3 = Arrays.asList(“kl”,”MN”,”op”);

//Combination

List<List<String>> input = Arrays.asList(system1,system2,system3);

Attempt 1: The input type is a List of List<String>.  We want to get all the strings from this input. We know that the map function helps us to transform an object. Will it help us here?  Let us take this step by step.


input.stream()
.map(list -> list)
.forEach(System.out::println)

The call to the input.stream()  returns a Stream<List<String>>

This gives an output:

[AB, CD, EF]

[GH, ij]

[kl, MN, op]

When we apply the map function, each time we are getting a list. But we need the individual elements in that list as a combined result. How do we get that?

When we have a single list as shown below and we applied the stream() to method to it, what happened?

List<String> strings = Arrays.asList(“A”,”b”,”C”);

strings.stream()

              .forEach(System.out::println);

This gave us the individual elements in that stream. So will applying the stream method to the list above solve the issue? Let’s try

Attempt 2:  Applying a stream to the list and using a map


input.stream()
.map(list -> list.stream())
.forEach(System.out::println)

This gives a weird output like this:

java.util.stream.ReferencePipeline$Head@87aac27

java.util.stream.ReferencePipeline$Head@3e3abc88

java.util.stream.ReferencePipeline$Head@6ce253f1

This gives us a stream of objects. So the usage of the map method in this scenario is not right. This is because the map method as mentioned earlier takes an input and produces one output. But in this case, the map method takes a list and we want the individual elements of that list to be combined together. This is not what the map function does. We need to use a different function.

Attempt 3: Using a flatMap


input.stream()
.flatMap(list -> list.stream())
.forEach(System.out::println);

This gives us the required output:

AB

cd

EF

GH

ij

kl

MN

Op

Let us break flatMap up into 2 operations:

map:

[ [AB, CD, EF]      [GH, ij]           [kl, MN, op] ]

  Stream 1             Stream 2           Stream 3

flatten it:

AB, cd, EF             GH, ij               kl ,MN ,op

The flatMap() does a map + flat. Flattening here is of the individual streams from each item in the list to a single stream. The flatMap() methods needs a stream and hence the list->list.stream().The flatMap method takes an input and can give either 0 or more elements.

Let us consider another example to understand this well. Let us consider 3 different football leagues. The English Premier league, the LIGA BBVA or the Spanish League and the Bundesliga. Each league has a list of teams. We can represent this as:


public class League {
private String leagueName;
private List<Team> teams;
}

view raw

League.java

hosted with ❤ by GitHub


public class Team
{
private String name;
public Team(String teamName){
this.name=teamName;
}
}

view raw

Team.java

hosted with ❤ by GitHub

Problem: Given a list of leagues, we need to return the names of the all the teams in the leagues.

Imperative style:


private static List<String> displayAllTeamNamesImperative(List<League> leagues){
List<String> teamNames = new ArrayList<>();
for(League league : leagues)
{
List<Team> teams = league.getTeams();
for(Team team : teams)
{
teamNames.add(team.getName());
}
}
return teamNames;
}

Declarative style using map:

We have a list of leagues. When we call stream() on it, it will operate on a single League object. But a league has multiple teams in it.  If we try solving this using map() then we land up getting this:


leagues.stream()
.map(league -> league.getTeams().stream())
.forEach(System.out::println);

Output:

java.util.stream.ReferencePipeline$Head@87aac27

java.util.stream.ReferencePipeline$Head@3e3abc88

java.util.stream.ReferencePipeline$Head@6ce253f1

We land up getting 3 streams. This means that the map operation is not the right fit here. We need a function that can take these streams and combine each of these elements in these streams to a unified output.

This is the scenario for a flatMap() as we have a collection of collections. So the input is  a collection of leagues and each league has another collection which is team.


private static List<String> displayAllTeamNamesFunctional(List<League> leagues)
{
return leagues.stream()
.flatMap(league ->league.getTeams().stream())
.map( team ->team.getName())
.collect(Collectors.toList());
}

When you have a collection of collections and want a unified output, use the flatMap.

I hope you have understood the basics of both map and flatMap methods and the scenarios in which they should be applied.