by BehindJava

Difference between Map and Flat Map

Home » java » Difference between Map and Flat Map

In this tutorial we are going to learn about the differences between Map and Flat Map in Java 8 which is very important question in the interview perspective.

Lets start with a real time example.

  • Due to pandemic all the employees are working from home so most of the MNC’s want to know the locations where employees are comfortable in working so that they can open ODC near there hometowns.
  • Lets assume the requirement like this,Where we have a list of employees and we need to get the list of cities where they have worked in the past years.

To fetch all those cities where all the emplyees have worked we can go with the below best practises i.e., Map and Flat Map.

Lets create an Employee.class because we need a list of employees so our employees class is going to going to have few fields like private id, name and cities worked and we will generate getters, setters and toString method because we need to print the list of employees and need to see the contents of the list.

import java.util.List;

public class Employee {

	private int id;
	private String name;
	private List<String> pastCitiesList;

	public Employee(int id, String name, List<String> pastCitiesList) {
		super();
		this.id = id;
		this.name = name;
		this.pastCitiesList = pastCitiesList;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<String> getPastCitiesList() {
		return pastCitiesList;
	}

	public void setPastCitiesList(List<String> pastCitiesList) {
		this.pastCitiesList = pastCitiesList;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", pastCitiesList=" + pastCitiesList + "]";
	}

}

With all the above things in place we will create another class i.e., Main.class where we will have all the main method and the logic to see how the Map and Flat Map is going to work in fetching the list of employees. In the real time we get data from the database for your understanding I have hardcoded the data into list.

import java.util.ArrayList;
import java.util.List;

public class Main {

	public static void main(String[] args) {
		List<String> pastCitiesWorked = new ArrayList<String>();
		pastCitiesWorked.add("Jodhpur");
		pastCitiesWorked.add("Mirjapur");
		pastCitiesWorked.add("Rampur");
		pastCitiesWorked.add("Ratanpur");

		Employee e = new Employee(1, "Munna Bhayya", pastCitiesWorked);

		List<String> pastCitiesWorked1 = new ArrayList<String>();
		pastCitiesWorked1.add("Guntur");
		pastCitiesWorked1.add("Ongole");
		pastCitiesWorked1.add("Kadapa");
		pastCitiesWorked1.add("Nellore");

		Employee e1 = new Employee(2, "Guddu Pandit", pastCitiesWorked1);

		List<String> pastCitiesWorked2 = new ArrayList<String>();
		pastCitiesWorked2.add("Jaladhar");
		pastCitiesWorked2.add("Phagwara");
		pastCitiesWorked2.add("Patiala");
		pastCitiesWorked2.add("Gurdaspur");

		Employee e2 = new Employee(3, "Ramesh Rao", pastCitiesWorked2);

		List<Employee> elist = new ArrayList<Employee>();
		elist.add(e);
		elist.add(e1);
		elist.add(e2);

		System.out.println(elist);
	}
}

This the following output we get when we run the Main.class.

[Employee [id=1, name=Munna Bhayya, pastCitiesList=[Jodhpur, Mirjapur, Rampur, Ratanpur]], Employee [id=2, name=Guddu Pandit, pastCitiesList=[Guntur, Ongole, Kadapa, Nellore]], Employee [id=3, name=Ramesh Rao, pastCitiesList=[Jaladhar, Phagwara, Patiala, Gurdaspur]]]

Now we will see about the working of Map and implementing it our Main.class.

How Map works?

  • The Stream.map() function performs map functional operation i.e., it takes a Stream and transforms it to another new Stream.
  • It applies a function on each element of Stream and stores return value into new Stream.
  • The map operation takes a function, which is called for each value in the input stream and produces one result value, which is sent to the output stream.

Lets say we need to get the list of all the employee id’s present in a company for this we can code the below without using Map.

List<Integer> ids = new ArrayList<Integer>();

		for (Employee emp : elist) {
			ids.add(emp.getId());
		}

		System.out.println(ids);

Output:

[1, 2, 3]

Instead of writing the above code for getting the list of employees it can be done in a single line using Map in Java 8.

List<Integer> ids = elist.stream().map(emp -> emp.getId()).collect(Collectors.toList());
		System.out.println(ids);

Output:

[1, 2, 3]

Note: Map creates a new Stream when a Map operation is done and hence existing list is not modified and a fuction is applied to each of its object on the stream and is collected to the type you want.

Now we will see How Flat Map works?

  • Is the combination of a Map and a Flat operation.
  • This means you first apply the map function and then flattens the result.
  • The key difference is the function used by map operation returns a Stream of values or a list of values rather than a single value, that’s why we need flattening. When you flat a Stream of Stream, it gets converted into Stream of values.
  • To understand what flattening a Stream consists in, Consider a structure like [[1,2,3],[4,5,6],[7,8,9]] which has “two levels”. Its basically a big List containing three more List. Flattening this means transforming it in a “one level” structure e.g. [1,2,3,4,5,6,7,8,9] i.e., Just one list.
  • flatmap() is flattening those multiple values into a single stream and remove duplicates by set.

Syntax using Flat Map

Set<String> citiesWorkedFlat = elist.stream().flatMap(emp -> emp.getPastCitiesList().stream())
				.collect(Collectors.toSet());
		System.out.println(citiesWorkedFlat);

Output:

[Ratanpur, Mirjapur, Kadapa, Jaladhar, Gurdaspur, Rampur, Phagwara, Patiala, Jodhpur, Guntur, Ongole, Nellore]

The beauty of Flat Map is an input will be in terms of its stream and output will be given in terms of strean again and that stream is going to be a single stream and every operation done on each object is going to append its output in one single stream only but not as a different streams.

In simpler words Flat Map flattens the 2D array into a single array as shown in the output above and since we have used set we will get unique values in the output.