Java8之map和flatMap

以前有點搞不懂這兩個概念,今天在scala裏面看到flatMap是等於map+flatten,把它扁平化的感覺。

就想用Java試一下,確實是降低維度,把它打平的感覺。

官方的一個解釋:

map:Returns a stream consisting of the results of applying the given function to the elements of this stream.

返回一個流,包含給定函數應用在流中每一個元素後的結果

flatmap:Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

返回一個流,包含將此流中的每個元素替換爲通過給定函數映射應用於每個元素而生成的映射流的內容

來一段代碼瞅瞅,造一下數據

        List<List<String>> res = new ArrayList<>();
        List<String> list = new ArrayList<>();
        for (int i = 1; i < 4; i++) {
            list.add(i + "");
        }
        List<String> list2 = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            list2.add(i + "");
        }

        res.add(list);
        res.add(list2);

        List<Stream<String>> collect1 = res.stream().map((li -> li.stream().map(s -> s + "處理"))).collect(Collectors.toList());
        List<String> collect2 = res.stream().flatMap(li -> li.stream().map(s -> s + "處理")).collect(Collectors.toList());
       

看結果:

用Debug設置斷點

發現:

collect1有兩層了,而collect2只有一層了,數據都在這一層下面。

用了flatMap確實降低了維度。只有一層了!覺得通俗易懂的給點個讚唄!

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