Wednesday 19 July 2023

Difference between map and flatMap method in Java Stream

     A Stream API is an important feature introduced in java 8, Stream is not a data structure means not stores any data and also not modifying the data but it will operate with the data source and to process data in convenient and faster. Stream API is a cleaner and more readable code.

Let us discuss the map and flatMap method usages and differences.

Use a map() of stream method if you just want to transform one Stream into another where each element gets converted to one single value. 

Use flatMap() of stream method if the function used by map operation returns multiple values and you want just one list containing all the values of the lists.

map method code example,

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

public class StreamMapExamples {
	
	public static void main(String[] args) {
		
		List<String> listOfStrings = Arrays.asList(new String[]{"abc", "bcd", "cde"});
		
		List<String> list = listOfStrings.stream()
				.map( s-> s.toUpperCase()).collect(Collectors.toList());
		
		list.stream().forEach(s-> System.out.println(s));
	}
	
}

the above code will print ABC, BCD and CDE.

flatMap code example,

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

public class StreamflatMapExample {
	
	public static void main(String[] args) {
		
		List<List<String>> listListOfStrings = new ArrayList<List<String>>();
		listListOfStrings.add(Arrays.asList(new String[]{"ABC", "BCD"}));
		listListOfStrings.add(Arrays.asList(new String[]{"CDE", "DEF"}));
		
		List<String> listOfStrings = listListOfStrings.stream().flatMap(s->s.stream()).collect(Collectors.toList());
		
		listOfStrings.stream().forEach(s-> System.out.println(s));
	}

}

The flatMap method converts list of strings of list into list of strings, the above code will print ABC, BCD, CDE and DEF.


No comments:

Post a Comment