Wednesday, 19 July 2023

Difference Between map() and flatMap() in Java Streams

     The Stream API is one of the most important features introduced in Java 8. A stream is not a data structure, which means it does not store any data. It also does not modify the original data. Instead, it operates on a data source, such as a collection or an array, and processes the data in a convenient and efficient manner.

The Stream API helps you write cleaner, more readable, and more maintainable code while performing operations such as filtering, mapping, sorting, and reducing data.

Let's discuss the usage and differences between the map() and flatMap() methods.

  • Use the map() method when you want to transform each element of a stream into exactly one corresponding element. In other words, one input element is mapped to one output element.

  • Use the flatMap() method when the mapping function returns multiple values (such as a collection or another stream) for each input element, and you want to flatten all those values into a single stream.

map() method 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() method 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 a list of lists of strings into a single list of strings by flattening the nested collections into one stream. The above code prints the following values:

ABC, BCD, CDE, and DEF.

No comments:

Post a Comment