Stream流中的flatMap

短命女 2023-07-23 06:55 46阅读 0赞
  1. @Test
  2. void contextLoads() {
  3. // 字符串判NULL
  4. List<Optional<String>> list = Arrays.asList (
  5. Optional.of("A"),
  6. Optional.empty(),
  7. Optional.of("B"));
  8. list.stream().flatMap(o->o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());
  9. // flatMap合并
  10. List<Integer> lists = Stream.of(Arrays.asList(1, 2, 3), Arrays.asList(4, 5))
  11. .flatMap(test -> test.stream()).collect(Collectors.toList());
  12. }
  13. # 简介
  14. flatMap() 这个方法主要是合并集合
  15. # 举栗子
  16. 一个数组是:[1,2,3],另外一个对象是:[4,5]
  17. 使用Stream.of(lists).flatMap(n -> n.stream()).collect(Collections.toList())
  18. 之后出现一个新数组:[1,2,3,4,5]

发表评论

表情:
评论列表 (有 0 条评论,46人围观)

还没有评论,来说两句吧...

相关阅读