Stream.map
Returns a stream consisting of the results of applying the givenfunction to the elements of this stream.
返回一个流,由将给定函数应用于该流的元素的结果组成。
示例:
List<String> nameList = Stream.of("ZhangSan", "Tom").collect(Collectors.toList());
nameList.stream().map(n -> n + ", welcome").forEach(e -> System.out.println(e));
输出:
ZhangSan, welcome
Tom, welcome
请注意另一种情况:
List<String> nameList = Stream.of("ZhangSan", "Tom").collect(Collectors.toList());
List<String[]> list = nameList.stream()
.map(n -> n.split(""))
.collect(Collectors.toList());
for (String[] strings : list) {
for (int i = 0; i < strings.length; i++) {
System.out.print(strings[i] + " ");
}
System.out.println();
}
输出:
Z h a n g S a n
T o m
map操作就是把一种操作运算,映射到一个序列的每一个元素上。以每个元素为一个单位,运算的结果也是相互独立的,所以返回的是
List<String[]>
,而不是List<String>
Stream.flatMap
Returns a stream consisting of the results of replacing each element ofthis stream with the contents of a mapped stream produced by applyingthe provided mapping function to each element. Each mapped stream is closed after its contentshave been placed into this stream. (If a mapped stream is nullan empty stream is used, instead.)
返回一个流,由将提供的映射函数应用到每个元素所产生的映射流的内容替换此流中的每个元素的结果组成。每个映射的流在其内容被放入该流后将被关闭。(如果映射流为null,则使用空流。)
The flatMap() operation has the effect of applying a one-to-manytransformation to the elements of the stream, and then flattening theresulting elements into a new stream.
flatMap()操作的效果是对流的元素应用一对多的转换,然后将产生的元素平铺成一个新的流。
示例:
List<String> nameList = Stream.of("ZhangSan", "Tom").collect(Collectors.toList());
List<String> list = nameList.stream()
.map(n -> n.split(""))
.flatMap(e -> Arrays.stream(e))
.collect(Collectors.toList());
System.out.println(list.toString());
输出:
[Z, h, a, n, g, S, a, n, T, o, m]