java集合和流的使用

來自於java 8實戰一書

package com.bobo.basic.jdk8.chapter5;

import com.alibaba.fastjson.JSONObject;
import com.bobo.basic.jdk8.Dish;

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

public class Section1 {

    public static List<Dish> menu = new ArrayList<>();

    static {
        menu = Arrays.asList(
                new Dish("pork", false, 800, Dish.Type.MEAT),
                new Dish("beef", false, 700, Dish.Type.MEAT),
                new Dish("chickren", 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)
        );
    }


    /**
     * 流中的filter方法
     */
    public static void test01() {
        List<Dish> collect = menu.stream().filter(Dish::isVegetarian).collect(Collectors.toList());
        System.out.println(collect.toString());
    }


    /**
     * distinct 去重
     */
    public static void test02() {
        List<Integer> list = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
        list.stream().filter(integer -> integer % 2 == 0)
                .distinct().forEach(integer -> {
            System.out.println(integer.toString());
        });
    }


    /**
     * 截斷
     */
    public static void test03() {
        List<Dish> collect = menu.stream().filter(dish -> dish.getCalories() > 300)
                .limit(3).collect(Collectors.toList());
        System.out.println(collect.toString());
    }


    /**
     * 跳過
     */
    public static void test04() {
        List<Dish> collect = menu.stream().filter(dish -> dish.getCalories() > 300)
                .skip(2).collect(Collectors.toList());
        System.out.println(collect.toString());
    }


    /**
     * 對流中的每一個元素應用函數: 接受一個函數作爲參數,然後應用到每個元素上,並將其映射爲一個新的元素,
     */
    public static void test05() {
        List<Integer> collect = menu.stream().map(Dish::getName).map(String::length).collect(Collectors.toList());
        System.out.println(collect.toString());
    }


    /**
     * 流的扁平化:
     * flatMap方法的效果是:各個數組並不是分別映射成爲一個流,而是映射成爲流的內容,所以使用flatMap(Arrays::stream)
     * 的時候是把生成的流都合併起來,扁平化一個流。
     */
    public static void test06() {
        List<String> strings = Arrays.asList("Hello", "World");
        List<String> collect = strings.stream().map(s -> s.split("")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
        System.out.println(JSONObject.toJSONString(collect));
    }


    /**
     * 是否至少匹配一個元素:
     * <p>
     * 流中能否有一個元素能匹配給定的謂詞
     */
    public static void test07() {
        if (menu.stream().anyMatch(Dish::isVegetarian)) {
            System.out.println("The menu is (somewhat) vegetarian friendly");
        }
    }


    /**
     * 所有的都匹配
     */
    public static void test08() {
        if (menu.stream().anyMatch(dish -> dish.getCalories() < 1000)) {
            System.out.println("菜譜的所有的熱量都小於1000");
        }
    }


    /**
     * 所有的都不匹配
     */
    public static void test09() {
        if (menu.stream().noneMatch(dish -> dish.getCalories() > 1000)) {
            System.out.println("菜譜的所有的熱量都小於1000");
        }
    }

    /**
     * findAny方法返回的是當前流中的任意元素:
     * 流水線在後臺進行優化使其只需要走一遍,在利用短路找到結果的時候立即結束
     * Optional是一個容器類,代表一個值存在或者不存在
     */
    public static void test10() {
        Optional<Dish> any = menu.stream().filter(Dish::isVegetarian).findAny();
        if (any.isPresent()) {
            System.out.println("有值");
        }
        /**
         * 當有值存在的時候會執行指定的代碼塊
         */
        any.ifPresent(dish -> {
            System.out.println(dish.getName());
        });

        //當有值的時候就會返回
        Dish dish = any.get();
    }


    /**
     * 查找第一個元素
     */
    public static void test11() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        Optional<Integer> first = list.stream().map(integer -> integer * integer).filter(integer -> integer % 3 == 0).findFirst();
        if (first.isPresent()) {
            System.out.println("exits");
        } else {
            System.out.println("no exits");
        }
    }


    /**
     * reduce 方法兩個參數
     *      第一個參數是初始值。
     *      第二個參數 BinaryOperator<T> accumulator 將兩個元素組合起來產生一個新值
     */

    public static void test12() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        Integer reduce = list.stream().reduce(0, (a, b) -> a + b);
        System.out.println(reduce);

        Optional<Integer> reduce1 = list.stream().reduce(Integer::max);
        if (reduce1.isPresent()) {
            System.out.println(reduce1.get());
        }
    }


    public static void main(String[] args) {
        test12();
    }
}

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