flatMap

定义

  1. <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

功能

将Function转化后的Stream合并成一个Stream。

案例

  1. @Test
  2. public void mergeMapValuesTest(){
  3. Map<Integer, ListContainer> map = Maps.newHashMap();
  4. List<AClass> aClassList1 = Lists.newArrayList();
  5. AClass aClass = new AClass(1, "zhuoli1", "haha1");
  6. aClassList1.add(aClass);
  7. aClassList1.add(new AClass(2, "zhuoli2", "haha2"));
  8. aClassList1.add(new AClass(3, "zhuoli3", "haha3"));
  9. List<AClass> aClassList2 = Lists.newArrayList();
  10. aClassList2.add(aClass);
  11. aClassList2.add(new AClass(5, "zhuoli5", "haha5"));
  12. aClassList2.add(new AClass(6, "zhuoli6", "haha6"));
  13. /*交集*/
  14. /*[AClass(id=1, name=zhuoli1, description=haha1)]*/
  15. List<AClass> intersectResult = aClassList1.stream().filter(aClassList2::contains).collect(Collectors.toList());
  16. System.out.println(intersectResult);
  17. /*并集*/
  18. List<AClass> unionResult = Stream.of(aClassList1, aClassList2).flatMap(Collection::stream).distinct().collect(Collectors.toList());
  19. assertEquals(unionResult.size(), 5);
  20. System.out.println(unionResult);
  21. /*差集*/
  22. /*[AClass(id=2, name=zhuoli2, description=haha2), AClass(id=3, name=zhuoli3, description=haha3)]*/
  23. List<AClass> differenceResult = aClassList1.stream().filter(x -> !aClassList2.contains(x)).collect(Collectors.toList());
  24. System.out.println(differenceResult);
  25. map.put(1, new ListContainer(aClassList1));
  26. map.put(2, new ListContainer(aClassList2));
  27. /*合并多个list*/
  28. List<AClass> aClassListResult = map.values().stream().flatMap(listContainer -> listContainer.getLst().stream()).collect(Collectors.toList());
  29. /*注意跟并集的区别*/
  30. assertEquals(aClassListResult.size(), 6);
  31. System.out.println(aClassListResult);
  32. }