java8 stream flatMap流的扁平化操作

  flatMap的用法和含义住要通过一个案例来讲解,

  案例:对给定单词列表 ["Hello","World"],你想返回列表["H","e","l","o","W","r","d"]

  第一种方式

  String[] words = new String[]{"Hello","World"};

  List a = Arrays.stream(words)

  .map(word -> word.split(""))

  .distinct()

  .collect(toList());

  a.forEach(System.out::print);

  代码输出为:[Ljava.lang.String;@12edcd21[Ljava.lang.String;@34c45dca

  (返回一个包含两个String[]的list)

  这个实现方式是由问题的,传递给map方法的lambda为每个单词生成了一个String[](String列表)。因此,map返回的流实际上是Stream 类型的。你真正想要的是用Stream来表示一个字符串。

  下方图是上方代码stream的运行流程

  第二种方式:flatMap(对流扁平化处理)

  String[] words = new String[]{"Hello","World"};

  List a = Arrays.stream(words)

  .map(word -> word.split(""))

  .flatMap(Arrays::stream)

  .distinct()

  .collect(toList());

  a.forEach(System.out::print);

  结果输出:HeloWrd

  使用flatMap方法的效果是,各个数组并不是分别映射一个流,而是映射成流的内容,所有使用map(Array::stream)时生成的单个流被合并起来,即扁平化为一个流。

  下图是运用flatMap的stream运行流程,

  //扁平化流

  //找出数组中唯一的字符

  String[] strArray = {"hello", "world"};

  //具体实现

  List res = Arrays.stream(strArray)

  .map(w -> w.split(""))

  .flatMap(Arrays::stream)

  .distinct()

  .collect(Collectors.toList());

  System.out.println(res);

  //TODO 案例

  System.out.println("--------------------------------");

  //Demo1:给定数组,返回数组平方和(直接使用映射)

  //[1,2,3,4]=>[1,4,9,16]

  Integer[] nums1 = {1, 2, 3, 4};

  List nums1List = Arrays.asList(nums1);

  List res1 = nums1List.stream().map(i -> i * i).collect(Collectors.toList());

  System.out.println(res1);

  System.out.println("--------------------------------");

  //Demo2:给定两数组,返回数组对

  //[1,2,3],[3,4]=>[1,3],[1,4],[2,3],[2,4],[3,3],[3,4]

  Integer[] nums2 = {1, 2, 3};

  Integer[] nums3 = {3, 4};无锡正规妇科 http://www.xasgyy.net/

  List nums2List = Arrays.asList(nums2);

  List nums3List = Arrays.asList(nums3);

  //使用2个map嵌套过滤

  List res2 = nums2List.stream().flatMap(i -> nums3List.stream().map(j -> new int[]{i, j})).collect(Collectors.toList());

  System.out.println(res2.size());

  System.out.println("--------------------------------");

  //Demo3:针对Demo2和Demo1组合返回总和能被3整除的数对

  //(2,4)和(3,3)是满足条件的

  List res3 = nums2List.stream().flatMap(i -> nums3List.stream().filter(j -> (i + j) % 3 == 0).map(j -> new int[]{i, j})).collect(Collectors.toList());

  System.out.println(res3.size());

  }

  }


猜你喜欢

转载自blog.51cto.com/14335413/2401399