java8 map flatmap

map: 對於Stream中包含的元素使用給定的轉換函數進行轉換操做,新生成的Stream只包含轉換生成的元素。這個方法有三個對於原始類型的變種方法,分別是:mapToInt,mapToLong和mapToDouble。這三個方法也比較好理解,好比mapToInt就是把原始Stream轉換成一個新的Stream,這個新生成的Stream中的元素都是int類型。之因此會有這樣三個變種方法,能夠免除自動裝箱/拆箱的額外消耗;javascript

map方法示意圖:
html

flatMap:和map相似,不一樣的是其每一個元素轉換獲得的是Stream對象,會把子Stream中的元素壓縮到父集合中;java

flatMap方法示意圖:
函數

 

 

原文地址

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

一句話

把幾個小的list轉換到一個大的list。this

一張圖

 
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<String> teamIndia = Arrays.asList("Virat", "Dhoni", "Jadeja"); List<String> teamAustralia = Arrays.asList("Warner", "Watson", "Smith"); List<String> teamEngland = Arrays.asList("Alex", "Bell", "Broad"); List<String> teamNewZeland = Arrays.asList("Kane", "Nathan", "Vettori"); List<String> teamSouthAfrica = Arrays.asList("AB", "Amla", "Faf"); List<String> teamWestIndies = Arrays.asList("Sammy", "Gayle", "Narine"); List<String> teamSriLanka = Arrays.asList("Mahela", "Sanga", "Dilshan"); List<String> teamPakistan = Arrays.asList("Misbah", "Afridi", "Shehzad"); List<List<String>> 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<String> listOfAllPlayers = new ArrayList<>(); for(List<String> 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<String> 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) 
相關文章
相關標籤/搜索