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]

 

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