java.util.stream.Stream
Interface. Both methods are intermediate functions for streams, in that, they do not produce a final result but are used to apply transformations on the elements of a Stream. It is possible to to chain multiple map() and flatMap() while processing a single stream.Both
map()
and flatMap()
both can be applied to a Stream<T>
and return a Stream<R>
or transformed elements, but the main difference is that map()
produces one output element for each input element, whereas flatMap()
produces any number (0-n) of output elements for each input element. Put simply, when using a map()
, the resulting stream would have same number or elements as the input stream, where as it can be wildly different in case of a flatMap. The following example illustrates the differences between these two methods.
If we take the example of a list of Strings which in turn are comma separated values as below
List<string> input = Arrays.asList("o,n,e", "t,w,o", "t,h,r,e,e", "f,o,u,r");
and try to split them in to individual characters, map() would return a list three lists, where as using flatMap, you can get a single list of individual characters, as shown below.</string>input.stream().map(x -> Arrays.asList(x.split(","))).forEach(x -> System.out.print(x + " --- "));
Output:[o, n, e] --- [t, w, o] --- [t, h, r, e, e] --- [f, o, u, r] ---
input.stream().flatMap(x -> Arrays.asList(x.split(",")).stream()).forEach(x -> System.out.print(x + " --- "));
Output:o --- n --- e --- t --- w --- o --- t --- h --- r --- e --- e --- f --- o --- u --- r ---
No comments:
Post a Comment