map
map() method -> Data Transformation
map() takes Stream
Stream
1 | <R> Stream<R> map(Function<? super T, ? extends R> mapper); |
It’s mapper function produces single value for each input value.hence it is also called One-To-One mapping.
这个方法比较好理解,把一个事物映射为另一个事物,是一对一的关系。
在没有stream.map()时,就在使用apache和guava的类似api
apache中的ListUtils1
public static <E> List<E> transformedList(final List<E> list,final Transformer<? super E, ? extends E> transformer)
guava中的Lists1
public static <F, T> List<T> transform(List<F> fromList, Function<? super F, ? extends T> function)
flatMap
flatMap() -> map() + Flattering
flatMap() takes Stream<Stream
Stream
1 | <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper); |
It’s mapper function produces multiple value for each input value.hence it is also called One-To-Many mapping.
flattering
flatMap()其实是两个方法的合并,map()好理解,主要是flattering。
Before Flattening: [[t,u], [v,w,x], [y,x]]
After Flattening: [t,u,v,w,x,y,x]
其实就是把两层数组打平了。
实例
在stackoverflow上找的一个示例:
What’s the difference between map() and flatMap() methods in Java 8?
flatMap helps to flatten a Collection<Collection
1 | public class Parcel { |
结果输出:1
2
3
4
5-------- Without flatMap() ---------------------------
collect() returns: [[Laptop, Phone], [Mouse, Keyboard]]
-------- With flatMap() ------------------------------
collect() returns: [Laptop, Phone, Mouse, Keyboard]
As you can see, with map() only:
- The intermediate type is Stream<List
- >
- The return type is List<List
- >
and with flatMap():
- The intermediate type is Stream
- The return type is List