1. 程式人生 > >Java8 第四章

Java8 第四章

alt get names 看電影 理學 his spa arr 執行

流操作可以順序執行也可以並行執行why.???

--Java API新成員==>遍歷數據集的高級叠代器

--特點:透明並行處理,無需寫多線程代碼

--因為filter、sorted、map和collect等操作是與具體線程模型無關的高層次構件,所以 它們的內部實現可以是單線程的,也可能透明地充分利用你的多核架構! ==>書中這句話不理解,解釋的很含糊!

//菜屬性
public class Dish {
    private final String name;
    private final boolean vegetarian;
    private final int calories;
    private final Type type;
?
public Dish(String name, boolean vegetarian, int calories, Type type) {
    this.name = name;
    this.vegetarian = vegetarian;
    this.calories = calories;
    this.type = type;
}
...getset...
@Override
public String toString() {
    return name;
}
public enum Type { MEAT, FISH, OTHER }
}
小例子:
public class Stream {
    public static void main(String[] args) {
        //菜單
        List<Dish> menu = Arrays.asList(
                new Dish("pork", false, 800, Dish.Type.MEAT),
                new Dish("beef", false, 700, Dish.Type.MEAT),
                new Dish("chicken", false, 400, Dish.Type.MEAT),
                new Dish("french fries", true, 530, Dish.Type.OTHER),
                new Dish("rice", true, 350, Dish.Type.OTHER),
                new Dish("season fruit", true, 120, Dish.Type.OTHER),
                new Dish("pizza", true, 550, Dish.Type.OTHER),
                new Dish("prawns", false, 300, Dish.Type.FISH),
                new Dish("salmon", false, 450, Dish.Type.FISH));
?
        List<String> threeHighCaloricDishNames = menu   //數據源
                .stream()                               //建立操作流水線
                .filter(x -> x.getCalories() > 300)     //取出熱量最高的
                .map(Dish::getName)                     //獲取菜名
                .limit(3)                                //選擇頭三個
                .collect(Collectors.toList());          //結果存在另一個List裏面
        System.out.println(threeHighCaloricDishNames);
    }
}


技術分享

map——接受一個Lambda,將元素轉換成其他形式或提取信息

collect——將流轉換為其他形式

流和集合的區別

--簡單理解 ==> 區別就在計算的時間

--集合 ==> 集合是一個內存中的數據結構, 它包含數據結構中目前所有的值——集合中的每個元素都得先算出來才能添加到集合中。(你可 以往集合裏加東西或者刪東西,但是不管什麽時候,集合中的每個元素都是放在內存裏的,元素 都得先算出來才能成為集合的一部分。

--流 ==> 流則是在概念上固定的數據結構(你不能添加或刪除元素),其元素則是按需計算的,從另一個角度來說,流就 像是一個延遲創建的集合:只有在消費者要求的時候才會計算值(用管理學的話說這就是需求驅 動,甚至是實時制造).

--舉個例子 ==> 集合就像你用dvd光盤看電影,而流則是用在線流媒體看電影(eg:愛奇藝網站上看)

--流只能遍歷一次

流操作

終端操作:關閉流的操作

中間操作:連接起來流的操作

 List<String> names = menu
                .stream()
                .filter(x -> {
                    System.out.println("filter"+x);
                    return x.getCalories() > 300;
                })
                .map(x->{
                    System.out.println("map"+x.getName());
                    return x.getName();
                })
                .limit(3)
                .collect(Collectors.toList());
        System.out.println(threeHighCaloricDishNames);
輸出:
filterpork
mappork
filterbeef
mapbeef
filterchicken
mapchicken
[pork, beef, chicken]
?
filter和map是兩個獨立的操作,但他們合並到同一次遍歷中===>循環合並技術

Java8 第四章