JDK1.8 -- Stream應用示例

package com.liutao.java8;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.*;

/**
 * @author: LIUTAO
 * @Date: Created in 2019/6/4  10:00
 * @Modified By:
 */
public class Data {
    private static List<PersonModel> list;

    static {
        PersonModel wu = new PersonModel("wu qi", 18, "男");
        PersonModel zhang = new PersonModel("zhang ba", 19, "男");
        PersonModel wang = new PersonModel("wang si", 20, "女");
        PersonModel zhao = new PersonModel("zhao wu", 20, "男");
        PersonModel chen = new PersonModel("chen liu", 21, "男");
        PersonModel chenTwo = new PersonModel("chen liu", 22, "男");
        list = Arrays.asList(wu, wang, zhang, zhao, chen, chenTwo);
    }

    public static List<PersonModel> getList() {
        return list;
    }

    /**
     * 演示filter的使用
     * <p>
     * (1)遍歷數據並檢測其中的元素時使用。
     * (2)filter接受一個函數作爲參數,該函數用Lambda表達式表示。
     */
    public static void testFilter() {
        List<PersonModel> data = Data.getList();

        //old,過濾所有男性
        List<PersonModel> temp = new ArrayList<>();
        for (PersonModel p : data) {
            if ("男".equals(p.getSex())) {

                temp.add(p);
            }
        }
        System.out.println(temp);

        //new,過濾所有女性
        temp = data
                .stream()
                .filter(personModel -> "女".equals(personModel.getSex()))
                .collect(toList());
        System.out.println(temp);
    }

    /**
     * 演示map的使用
     * <p>
     * (1)map生成的是一個一對一的映射,for的作用
     * (2)比較常用
     * (3)而且簡單
     */
    public static void testMap() {
        List<PersonModel> data = Data.getList();

        //獲取所有name
        List<String> names = data.stream().map(PersonModel::getName).collect(toList());
        System.out.println(names);
    }

    /**
     * 演示distinct的使用
     * <p>
     * 去除重複元素,這個方法是通過類的equals方法來判斷兩個元素是否相等
     */
    public static void testDistinct() {
        List<PersonModel> data = Data.getList();
        System.out.println(data.stream().distinct().collect(toList()));
    }

    /**
     * 演示sorted的使用
     * <p>
     * 如果流中元素的類實現了Comparable接口,即有自己的排序規則,則可以直接調用sorted()函數對元素進行排序,
     * 反之, 需要調用 sorted((T, T) -> int) 實現 Comparator 接口
     */
    public static void testSorted() {
        List<PersonModel> data = Data.getList();
        System.out.println(data.stream().sorted().collect(toList()));
        System.out.println(data.stream().sorted(Comparator.comparing(PersonModel::getName)).collect(toList()));
    }

    /**
     * 演示limit(long n)的使用
     * <p>
     * 返回前n個元素
     */
    public static void testLimit() {
        List<PersonModel> data = Data.getList();
        System.out.println(data.stream().limit(1).collect(toList()));
    }

    /**
     * 演示skip(long n)的使用
     * <p>
     * 去除前n個元素
     */
    public static void testSkip() {
        List<PersonModel> data = Data.getList();
        System.out.println(data.stream().skip(5).collect(toList()));
    }


    /**
     * 演示flatMap的使用
     * <p>
     * 將流中每一個元素T映射成一個流,再把每一個流連接成一個流
     */
    public static void testFlatMap() {
        List<String> list = new ArrayList<>();
        list.add("aaa bbb ccc");
        list.add("ddd eee fff");
        list.add("ggg hhh iii");
        List<String[]> str = list.stream().map(s -> s.split(" ")).collect(Collectors.toList());
        System.out.println(str);

        System.out.println(str.stream().flatMap(Arrays::stream).collect(Collectors.toList()));
    }

    /**
     * 演示anyMatch(T -> boolean)函數的使用
     *
     * 流中是否有一個元素匹配T -> boolean條件
     * 對應的其他函數如下:
     * allMatch(T -> boolean):流中是否所有元素匹配T -> boolean條件
     * noneMatch(T -> boolean):流中是否沒有元素匹配T -> boolean條件
     */
    public static void testAnyMatch(){
        List<PersonModel> data = Data.getList();
        System.out.println(data.stream().allMatch(personModel -> personModel.getAge() != null & personModel.getAge() > 30));
    }


    /**
     * 演示findAny()的使用
     *
     * 找到其中一個元素 (使用 stream() 時找到的是第一個元素;使用 parallelStream() 並行時找到的是其中一個元素)
     * findFirst():找到第一個元素
     */
    public static void testFindAny(){
        List<PersonModel> data = Data.getList();
        Optional<PersonModel> optional = data.stream().findAny();
        System.out.println(optional.get());
    }

    /**
     * 演示reduce的使用
     * <p>
     * 用於組合流中的元素,如求和,求積,求最大值等
     */
    public static void testReduce() {
        List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);
        Integer reduce = nums.stream().reduce(0, (x, y) -> x + y);
        System.out.println(reduce);
    }

    /**
     * 演示collect的使用
     * collect在流中生成列表、map等常用數據結構
     */
    public static void testCollect() {
        List<PersonModel> data = Data.getList();

        //生成list
        List<String> names = data.stream().map(PersonModel::getName).collect(toList());
        System.out.println(names);

        //生成set
        Set<String> sexs = data.stream().map(PersonModel::getSex).collect(toSet());
        System.out.println(sexs);

        //生成map
        Map<String, Integer> map = data.stream().collect(toMap(PersonModel::getName, PersonModel::getAge));
        System.out.println(map);

        //指定類型
        TreeSet<PersonModel> personModels = data.stream().collect(toCollection(TreeSet::new));
        System.out.println(personModels);

        //分組
        Map<Boolean, List<PersonModel>> collect = data.stream().collect(Collectors.groupingBy(per -> "男".equals(per.getSex())));
        System.out.println(collect);

        //分隔
        String str = data.stream().map(PersonModel::getName).collect(joining(",", "{", "}"));
        System.out.println(str);
    }

    /**
     * 演示Optional的使用
     * <p>
     * Optional是爲核心類庫新設計的一個數據類型,用來替換null。
     */
    public static void testOptional() {
        PersonModel personModel = new PersonModel();

        //對象爲空則打印出 -,personModel不能爲空,否則報錯
        Optional<Object> o = Optional.of(personModel);
        System.out.println(o.isPresent() ? o.get() : "-");

        //名稱爲空則打印出 - ,此處的名稱可以爲空
        Optional<String> name = Optional.ofNullable(personModel.getName());
        System.out.println(name.isPresent() ? name.get() : "-");

        //如果不爲空,則打印出xxx
        Optional.ofNullable("test").ifPresent(na -> System.out.println(na + "ifPresent"));

        //如果空,則返回指定字符串
        System.out.println(Optional.ofNullable(null).orElse("-"));
        System.out.println(Optional.ofNullable("1").orElse("-"));


        //如果空,則返回指定方法,或者代碼
        System.out.println(Optional.ofNullable(null).orElseGet(() -> {
                    return "hahaha";
                }
        ));

        System.out.println(Optional.ofNullable("1").orElseGet(() -> {
                    return "hahaha";
                }
        ));

    }

    /**
     * 演示parallelStream的使用
     * <p>
     * 輸出爲:
     * old:48
     * syn:1846
     * con:172
     * 從上面的輸出結果我們可以看到,con的速度要比syn快很多
     */
    public static void testParallelStream() {
        List<Integer> list = new ArrayList<>();
        for (Integer i = 0; i < 10000000; i++) {
            list.add(i);
        }

        //old
        List<Integer> temp1 = new ArrayList<>(10000000);
        long start = System.currentTimeMillis();
        for (Integer i : list) {
            temp1.add(i);
        }
        System.out.println("old:" + (System.currentTimeMillis() - start));

        //同步
        long start1 = System.currentTimeMillis();
        list.stream().collect(Collectors.toList());
        System.out.println("syn:" + (System.currentTimeMillis() - start1));

        //併發
        long start2 = System.currentTimeMillis();
        list.parallelStream().collect(Collectors.toList());
        System.out.println("con:" + (System.currentTimeMillis() - start2));
    }

    public static void main(String[] args) {
//        testFilter();
//        testMap();
//        testReduce();
//        testCollect();
//        testOptional();
//        testParallelStream();
//        testDistinct();
//        testSorted();
//        testLimit();
//        testSkip();
//        testFlatMap();
//        testAnyMatch();
        testFindAny();

        /**
         * 其餘的函數
         * count():返回流中元素個數,結果爲 long 類型
         * forEach():遍歷元素
         *
         */
    }
}

 

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