Map:

  • If you want to transform into single value then use Map
  • The map method is used to apply a function to each element in a stream, and return a new stream with the modified elements
public class MapFlatMapExample {

	public static void main(String[] args) {
		List<String> names = Stream.of(new User("Jayaram",101), new User("Vijay",102), new User("Test",103),
				new User("Hello",104), new User("Raj",105))
				.map(User::getUserName)
				.collect(Collectors.toList());
		System.out.println(names);
	}
}
Output: [Jayaram, Vijay, Test, Hello, Raj]

FlatMap

  • Used to flatten Nested collection list
  • If you want each element will be transformed to multiple values and the resulting stream needs to be converted to list then use FlatMap.
  • The flatMap method is similar, but instead of returning a stream of modified elements, it returns a stream of elements from the elements of the original stream. The function passed to flatMap is responsible for returning a stream of new elements, and these streams are then “flattened” into a single stream.
public class MapFlatMapExample {

	public static void main(String[] args) {
		List<List<User>> Users =   Arrays.asList(Arrays.asList(new User("Jayaram",101),new User("Raju",102)), Arrays.asList(new User("Vijay",104),new User("Vinay",105)));
		List<User> flattnedUsers  = Users.stream().flatMap(Collection::stream).collect(Collectors.toList());
		flattnedUsers.stream().map(User::getUserName).forEach(System.out::print);
		System.out.println(flattnedUsers);
		
	}
}
output:JayaramRajuVijayVinay
public class FlatMapExample {

	public static void main(String[] args) {
		
		List<List<Integer>> list = Arrays.asList(Arrays.asList(1,2), Arrays.asList(3,4));
		List<Integer> flattedList = list.stream().flatMap(Collection::stream).collect(Collectors.toList());
		System.out.println(flattedList);
	}
}
Output: [1, 2, 3, 4]

In the above code, you have Nested List that needs to be flattened to Single List. In this case, use flatMap

Thanks for Reading