Stream流的映射

  • 映射

映射是一种常见的从某些对象中选择对象的数据处理方法。

map:流支持map方法,它会接受一个函数作为参数。这个函数会被应用到每个元素上,并将其映射成一个新的元素。注意结果是一个新的元素,而不是去修改源数据。列如:下面的案例是将words数组的每个元素的长度映射成一个新的数组。


List<String> words =Arrays.asList("hello","world","In","devrlophm");
List<Integer> wordLengths =words.stream().map(String::length).collect(toList());

流的扁平化处理

Arrays.stream()的方法可以接受一个数组并产生一个流。

flatmap方法让你把一个流中的每个值都换成另一个流,然后把所有的流连接起来成为一个流。

例如根据words数组的形成一个新的,不重复的流为G、o、d、b、y、e、W、r、l。


String[] words = {"Goodbye", "World"};
worlds.stream().map(w->w.split("")).flatMap(Arrays::stream()).distinct();

给定列表int [] list1[1, 2, 3]和列表[3, 4],应该返回[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]。如果加个条件只返回总和能被3整除的数对呢?


List<Integer> num1 = Arrays.asList(1, 2, 3);//构成数组
List<Integer> num2 = Arrays.asList(3, 4);//构成数组
List<int[]> resultList=num1.stream().flatMap(i->num2.stream().map(j->new int[]{i,j})).collect.(toList());

用filter添加一个总和能被3整除。


List<int[]> pairs = num1.stream().flatMap(i ->num2.stream().filter(j -> (i + j) % 3 == 0) 
.map(j -> new int[]{i, j})).collect(toList());

版权声明:
作者:Gomo
链接:https://www.develophm.com/index.php/stream%e6%b5%81%e7%9a%84%e6%98%a0%e5%b0%84/415/
来源:开发之家
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>