Java 8 中 map() 和 flatMap()的那些事

兩個方法的背景

這兩個方法看起來作着一樣的事情,但實際上又有些不同。看源碼部分是這樣的html

package java.util.stream;

map()方法java

/**
* @param <R> The element type of the new stream
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
*               function to apply to each element
* @return the new stream
*/
    <R> Stream<R> map(Function<? super T, ? extends R> mapper);

flatMap()方法app

/**
* @param <R> The element type of the new stream
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element which produces a stream
* of new values
* @return the new stream
*/
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

Stream map() Method

看源碼作推測,map是一種中間操做,返回的是Streamless

代碼測試函數

map()方法測試

public static void main(String[] args) {
        System.out.println("Output with simple list");
        List<String> vowels = Arrays.asList("A", "E", "I", "O", "U");
        vowels.stream().map(vowel -> vowel.toLowerCase())
                .forEach(value -> System.out.println(value));
        List<String> haiList = new ArrayList<>();
        haiList.add("hello");
        haiList.add("hai");
        haiList.add("hehe");
        haiList.add("hi");
        System.out.println("Output with nested List of List<String>");
        List<String> welcomeList = new ArrayList<>();
        welcomeList.add("You got it");
        welcomeList.add("Don't mention it");
        welcomeList.add("No worries.");
        welcomeList.add("Not a problem");
        List<List<String>> nestedList = Arrays.asList(haiList, welcomeList);
        nestedList.stream().map(list -> {
            return list.stream().map(value -> value.toUpperCase());
        }).forEach(value -> System.out.println(value));
    }

Outputcode

Output with simple list
a
e
i
o
u
Output with nested List of List<String>
java.util.stream.ReferencePipeline$3@3b9a45b3
java.util.stream.ReferencePipeline$3@7699a589

flatMap()方法htm

public static void main(String[] args) {
        List<String> haiList = new ArrayList<>();
        haiList.add("hello");
        haiList.add("hai");
        haiList.add("hehe");
        haiList.add("hi");
        System.out.println("Output with nested List of List<String>");
        List<String> welcomeList = new ArrayList<>();
        welcomeList.add("You got it");
        welcomeList.add("Don't mention it");
        welcomeList.add("No worries.");
        welcomeList.add("Not a problem");
        List<List<String>> nestedList = Arrays.asList(haiList, welcomeList);
        nestedList.stream().flatMap(
                list -> list.stream())
                .map(value -> value.toUpperCase())
                .forEach(value -> System.out.println(value));
    }

Outputip

Output with nested List of List<String>
HELLO
HAI
HEHE
HI
YOU GOT IT
DON'T MENTION IT
NO WORRIES.
NOT A PROBLEM

Java 8 map() vs flatMap()

  • map()和flatMap()方法均可以應用於Stream <T>和Optional <T>。 而且都返回Stream <R>或Optional <U>。
  • 區別在於,映射操做爲每一個輸入值生成一個輸出值,而flatMap操做爲每一個輸入值生成任意數量(零個或多個)的值。 在flatMap()中,每一個輸入始終是一個集合,能夠是List或Set或Map。 映射操做採用一個函數,該函數將爲輸入流中的每一個值調用,並生成一個結果值,該結果值將發送到輸出流。 flatMap操做採用的功能在概念上想消耗一個值併產生任意數量的值。 可是,在Java中,方法返回任意數量的值很麻煩,由於方法只能返回零或一個值。

代碼element

public static void main(String[] args) {

        List<Stream> together = Stream.of(Arrays.asList(1, 2), Arrays.asList(3, 4)) // Stream of List<Integer>
                .map(List::stream)
                .collect(Collectors.toList());

        System.out.println("Output with map() -> "+together);


        List<Integer> togetherFlatMap = Stream.of(Arrays.asList(1, 2), Arrays.asList(3, 4)) // Stream of List<Integer>
                .flatMap(List::stream)
                .map(integer -> integer + 1)
                .collect(Collectors.toList());

        System.out.println("Output with flatMap() -> "+togetherFlatMap);
    }

Output

Output with map() -> [java.util.stream.ReferencePipeline$Head@16b98e56, java.util.stream.ReferencePipeline$Head@7ef20235]
Output with flatMap() -> [2, 3, 4, 5]
相關文章
相關標籤/搜索