Difference between Map() and Flatmap() in Java

Java Course in Chennai

The flatmap() and map() are the essential functionality in Java 8. Flatmap() and map() methods represents functional operation and also both are also methods in java.util.stream.Stream class. The major difference between map() and flatmap() is when we use map() function, it execute a function on every element of stream and stores the value which is returned by the function into a new stream. This way a stream is transformed into a new stream. For example String stream is transformed into integer stream where every element length is according to the stream. One major consideration is the function that is used for transformation in map() which returns a unique value. When you use flatmap(), it helps to flat that into a stream of values. Java Training in Chennai is the right option to enhance your career in Java map() and flatmap() function.

For e.g. If you have string stream {“12”, “34”} and a method getpermutations () returns lists of permutations of a string. When you implement the function in every stream string using map you will have [[“12”, “21”], [“34”, “43”]], but when you use flatmap() in JAVA method you get like [“12”, “21”, “34”, “43”].

Stream.map() works in Java 8

List listOfIntegers = Stream.of(“1”, “2”, “3”, “4”)



Stream.flatmap() works in Java 8

List ev = Arrays.asList(6, 8, 10);

List od = Arrays.asList(11, 13, 17);

List pri = Arrays.asList(2, 3, 5, 7, 11);

List num= Str.of(evens, odds, primes)

                       .flatMap(list -> list.str ())


System.out.println(“list: ” + num);

Output:  list: [2, 4, 6, 3, 5, 7, 2, 3, 5, 7, 11]

Understanding the map() and flatmap() function is not that much easy. Make use of this article to understand the concept of map() and flatmap() function. Go with any Java Course in Chennai. Java is one of the top programming languages in IT industry, the usage of this programming language is increasing tremendously. Even though many programming languages has been evolving every year Java beat the all other language and stood first in giving the excellent result to the customer through its advanced features. Be up to date in current trending language and explore yourself as a well professional Java programmer.

Leave a Reply

Required fields are marked*