Java8:如何使用flatMap()

原文地址

http://www.java67.com/2016/03/how-to-use-flatmap-in-java-8-stream.html

一句话

把几个小的list转换到一个大的list。

一张图

Java8:如何使用flatMap()_第1张图片
flatMap操作

一段代码

package test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Java Program to demonstrate how to use the flatMap() function in Java 8.
 * The flatMap() function is used to convert a Stream of list of values to
 * just a Stream of values. This is also called flattening of stream.
 *
 * @author Javin Paul
 */
public class Test {

    public static void main(String args[]) {

        List teamIndia = Arrays.asList("Virat", "Dhoni", "Jadeja");
        List teamAustralia = Arrays.asList("Warner", "Watson", "Smith");
        List teamEngland = Arrays.asList("Alex", "Bell", "Broad");
        List teamNewZeland = Arrays.asList("Kane", "Nathan", "Vettori");
        List teamSouthAfrica = Arrays.asList("AB", "Amla", "Faf");
        List teamWestIndies = Arrays.asList("Sammy", "Gayle", "Narine");
        List teamSriLanka = Arrays.asList("Mahela", "Sanga", "Dilshan");
        List teamPakistan = Arrays.asList("Misbah", "Afridi", "Shehzad");
        
        List> playersInWorldCup2016 = new ArrayList<>();
        playersInWorldCup2016.add(teamIndia);
        playersInWorldCup2016.add(teamAustralia);
        playersInWorldCup2016.add(teamEngland);
        playersInWorldCup2016.add(teamNewZeland);
        playersInWorldCup2016.add(teamSouthAfrica);
        playersInWorldCup2016.add(teamWestIndies);
        playersInWorldCup2016.add(teamSriLanka);
        playersInWorldCup2016.add(teamPakistan);
        
        // Let's print all players before Java 8
        List listOfAllPlayers = new ArrayList<>();
        
        for(List team : playersInWorldCup2016){
            for(String name : team){
                listOfAllPlayers.add(name);
            }
        }
        
        System.out.println("Players playing in world cup 2016");
        System.out.println(listOfAllPlayers);
        
        
        // Now let's do this in Java 8 using FlatMap
        List flatMapList = playersInWorldCup2016.stream()
                                                        .flatMap(pList -> pList.stream())
                                                        .collect(Collectors.toList());
        
        System.out.println("List of all Players using Java 8");
        System.out.println(flatMapList);
    }

}

Output
run:
Players playing in world cup 2016
[Virat, Dhoni, Jadeja, Warner, Watson, Smith, Alex, Bell, Broad, Kane, Nathan, Vettori, AB, Amla, Faf, Sammy, Gayle, Narine, Mahela, Sanga, Dilshan, Misbah, Afridi, Shehzad]
List of all Players using Java 8
[Virat, Dhoni, Jadeja, Warner, Watson, Smith, Alex, Bell, Broad, Kane, Nathan, Vettori, AB, Amla, Faf, Sammy, Gayle, Narine, Mahela, Sanga, Dilshan, Misbah, Afridi, Shehzad]
BUILD SUCCESSFUL (total time: 0 seconds)

你可能感兴趣的:(Java8:如何使用flatMap())