By the way, this is also a popular Java Stream and Lambda question and if you are going for an interview, it's better to revise concepts and understand the difference between map and flatmap better. In this article, we'll see a couple of working examples to understand the difference between map() and flatmap() in Java better. When you apply that function into each String of Stream using map you will get something like ,], but if you use flatmap, you get a Stream of Strings e.g. If map() uses a function, which, instead of returning a single value returns a Stream of values then you have a Stream of Stream of values, and flatmap() is used to flat that into a Stream of values.įor example, if we have a Stream of String containing, and a method getPermutations() which returns a list of permutations of given String. The key thing to remember is that the function used for transformation in the map() returns a single value. This way one stream is transformed into another like a Stream of String is transformed into a Stream of Integer where each element is the length of the corresponding Stream. The key difference between map() and flatmap() function is that when you use a map(), it applies a function on each element of the stream and stores the value returned by the function into a new Stream. Both represent functional operation and they are also methods in class but the map is used for transformation and flatmap is used for both transformation and flattening, that's why it's called the flatmap. The map() and flatmap() are two important operations in the new functional Java 8.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |