【笔记】两个示例说明map和flatMap的区别

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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值