Stream流中的flatMap

    @Test
    void contextLoads() {
        // 字符串判NULL
        List<Optional<String>> list = Arrays.asList (
                Optional.of("A"),
                Optional.empty(),
                Optional.of("B"));
        list.stream().flatMap(o->o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());

        // flatMap合并
        List<Integer> lists = Stream.of(Arrays.asList(1, 2, 3), Arrays.asList(4, 5))
                .flatMap(test -> test.stream()).collect(Collectors.toList());
    }
# 简介

flatMap() 这个方法主要是合并集合

# 举栗子

一个数组是:[1,2,3],另外一个对象是:[4,5]
使用Stream.of(lists).flatMap(n -> n.stream()).collect(Collections.toList())
之后出现一个新数组:[1,2,3,4,5]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章