Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Java is essentially an object-oriented language but has numerous functional programming techniques. Processing collections of objects is done using the Stream API was first introduced in Java 8. A stream is a collection of objects that supports several different operations and that may be pipelined to create the desired outcome.
Streams convey the outcome of the pipelined techniques; they do not alter the underlying data structure.
The stream is marked by terminal operations, which also yield the outcome.
Functional programming gave rise to the functions map() and flatMap() and in this blog, we will look at the difference between map() and flatmap().
A stream that contains the output of applying the specified function to each element of this stream is returned by the stream map function. A Stream instance is used as input by intermediate operations, which are then used to process another Stream object and return a new Stream instance.
Syntax:
For Stream
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
You can also try this code with Online Java Compiler
Here, R is the newly created stream's element type. Interface T is a stream, and stream components of type T are streams. When applied to each element, the stateless function known as a "mapper" creates a new stream and returns it.
When we need to map the components of a sure collection to a specific function and subsequently need to return the stream with the updated results, we may use this method, which is a difference between map() and flatmap().
public <U> Optional<U> map(Function<? super T, ? extends U> mapper)
The map() function can also be used with the Optional class in Java, which is a container object that may or may not contain a non-null value. The map() function on Optional applies a given function to the value in the Optional if it's present and returns a new Optional containing the result of the transformation. If the original Optional is empty, the map() function returns an empty Optional.
Usage and Example
Stream map() function with the operation of number + 5 on each element of the stream
Implementation:
Java
Java
import java.util.*; public class addition { public static void main(String[] args) { List<Integer>list=Arrays.asList(2, 5, 10, 15, 25); list.stream().map(number -> number + 5).forEach(System.out::println); } }
You can also try this code with Online Java Compiler
This Java code defines a class named addition with a main method that performs the following operations:
Creates a List<Integer> using the Arrays.asList() method and initializes it with the integers 2, 5, 10, 15, and 25.
Calls the stream() method on the List object to create a stream of its elements.
Calls the map() method on the stream and passes in a lambda expression as an argument. The lambda expression takes each element in the stream and adds 5 to it, returning the result as a new element.
Calls the forEach() method on the resulting stream, passing in a method reference System.out::println. This will print each element of the stream to the console.
What is flatMap() Method?
The stream flatMap function returns a stream containing the contents of a mapped stream formed by applying a mapping function to each element in the original stream.
Upon placing its contents into this stream, each mapped stream is shut down. A stream that contains nothing is utilized in its place if a mapped stream is null.
Since we can't flatten our string using a map, we may use flatMap() when we need to flatten or change the string () which is a prominent difference between map() and flatmap().
flatMap() = map() + Flattening. A flatMap() combines two operations; transformation and flattening of a stream of values into another stream that only consists of a single list storing values.
For Optional
public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper)
The flatMap() function on Optional applies a given function to the value in the Optional if it's present, and returns a new Optional that is the result of the flattened stream. If the original Optional is empty, the flatMap() function returns an empty Optional.
Usage and Example
Getting the 1st character of all the strings present in a list of strings and returning the result in the form of a stream.
This Java code demonstrates how to use the flatMap() method of the Stream class to convert a list of lists into a single list.
First, two lists of integers are created using the Arrays.asList() method. These lists are then stored in another list called ListofInts, which is a list of lists.
Next, the flatMap() method is called on ListofInts. This method flattens the list of lists into a single stream of integers by first calling the stream() method on each list in ListofInts, and then flattening the resulting streams into a single stream of integers. The resulting stream is then collected into a list using the Collectors.toList() method.
Finally, the original ListofInts and the flattened list listofInts are printed to the console.
public class MapExample { public static <T, R> List<R> map(List<T> list, Function<T, R> mapper) { List<R> result = new ArrayList<>(list.size()); for (T item : list) { R mappedItem = mapper.apply(item); result.add(mappedItem); } return result; }
public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4, 5); List<Integer> squaredNumbers = map(numbers, x -> x * x); System.out.println(squaredNumbers); // prints [1, 4, 9, 16, 25] } }
You can also try this code with Online Java Compiler
The flatMap() function is used instead of map() when the transformation applied to each element of a collection returns another collection, and we want to flatten the resulting collection of collections into a single collection.
What is the difference between map and flatMap and a good use case for each?
`map` transforms each element in a stream into another form individually, while `flatMap` transforms each element into a stream and flattens the result. Use `map` for one-to-one transformations and `flatMap` for one-to-many transformations, such as flattening nested collections.
What is the difference between flat map and map C++?
In C++, the map function applies a given function to each element in a collection and returns a new collection of the same size. In contrast, the flat_map function first applies a function to each element in a collection, then flattens the resulting nested collections into a single stream.
Conclusion
In this blog, we have discussed the difference between flatmap and map functions with some examples to understand their workings.
If you think this blog has helped you enhance your knowledge about the above question, and if you want to learn more, check out our articles: