Java - Lambda 快速入門

package com.imooc;

/**
 * 用戶身份認證標記接口
 */
@FunctionalInterface
public interface IUserCredential {

    /**
     * 通過用戶賬號,驗證用戶身份信息的接口
     * @param username 要驗證的用戶賬號
     * @return 返回身份信息[系統管理員、用戶管理員、普通用戶]
     */
    String verifyUser(String username);

//    boolean test();

    default String getCredential(String username) {
        // 模擬方法
        if ("admin".equals(username)) {
            return "admin + 系統管理員用戶";
        } else if("manager".equals(username)){
            return "manager + 用戶管理員用戶";
        } else {
            return "commons + 普通會員用戶";
        }
    }
}
package com.imooc;

/**
 * 消息傳輸格式化轉換接口
 */
@FunctionalInterface
public interface IMessageFormat {

    /**
     * 消息轉換方法
     * @param message 要轉換的消息
     * @param format 轉換的格式[xml/json..]
     * @return 返回轉換後的數據
     */
    String format(String message, String format);

//    boolean test();
    String toString();

    /**
     * 消息合法性驗證方法
     * @param msg 要驗證的消息
     * @return 返回驗證結果
     */
    static boolean verifyMessage(String msg) {
        if (msg != null) {
            return true;
        }
        return false;
    }
}
package com.imooc.impl;

import com.imooc.IUserCredential;

/**
 * Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
 * FileName: com.imooc.impl UserCredentialImpl
 * <p>TODO</p>
 *
 * @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
 * @version 1.00
 */
public class UserCredentialImpl implements IUserCredential {
    @Override
    public String verifyUser(String username) {
        if ("admin".equals(username)) {
            return "系統管理員";
        } else if("manager".equals(username)) {
            return "用戶管理員";
        }
        return "普通會員";
    }
}
package com.imooc.impl.impl;

import com.imooc.IMessageFormat;

/**
 * Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
 * FileName: com.imooc.impl.impl MessageFormatImpl
 * <p>TODO</p>
 *
 * @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
 * @version 1.00
 */
public class MessageFormatImpl implements IMessageFormat {
    @Override
    public String format(String message, String format) {
        System.out.println("消息轉換...");
        return  message;
    }
}
package imooclambda;

import com.imooc.IMessageFormat;
import com.imooc.IUserCredential;
import com.imooc.impl.UserCredentialImpl;
import com.imooc.impl.impl.MessageFormatImpl;
import java.util.Random;
import java.util.UUID;
import java.util.function.*;

/**
 * Hello world!
 *
 * 需求改動:
 *  所有的用戶驗證,可以同時獲取用戶的驗證信息[是否認證成功|成功~返回用戶|null]
 *
 *  Lambda表達式 基本語法
 */
public class App 
{
    String welcome = "慕課網歡迎您.";
    public static void main( String[] args ) {
		// 一、接口的靜態方法和默認方法

		// 1. 默認方法
		IUserCredential ic = new UserCredentialImpl();
		System.out.println(ic.verifyUser("admin"));
		System.out.println(ic.getCredential("admin"));

		// 2. 靜態方法
		String msg = "hello world";
		if (IMessageFormat.verifyMessage(msg)) {
		   IMessageFormat format = new MessageFormatImpl();
		   format.format(msg, "json");
		}

		// 匿名內部類,實現接口的抽象方法
		IUserCredential ic2 = new IUserCredential() {
		   @Override
		   public String verifyUser(String username) {
		       return "admin".equals(username)?"管理員":"會員";
		   }
		};

		// 二、lambda表達式 是 函數式接口的一種實現
		System.out.println(ic2.verifyUser("manager"));
		System.out.println(ic2.verifyUser("admin"));

		// lambda表達式,針對函數式接口的簡單實現
		IUserCredential ic3 = (String username) -> {
		   return "admin".equals(username)?"lbd管理員": "lbd會員";
		};

		System.out.println(ic3.verifyUser("manager"));
		System.out.println(ic3.verifyUser("admin"));
    }
}

/*
    java.util.function提供了大量的函數式接口
    Predicate 接收參數T對象,返回一個boolean類型結果
    Consumer 接收參數T對象,沒有返回值
    Function 接收參數T對象,返回R對象
    Supplier 不接受任何參數,直接通過get()獲取指定類型的對象
    UnaryOperator 接口參數T對象,執行業務處理後,返回更新後的T對象
    BinaryOperator 接口接收兩個T對象,執行業務處理後,返回一個T對象
 */
// 三、JDK8 提供的常見函數式接口
Predicate<String> pre = (String username) -> {
   return "admin".equals(username);
};

System.out.println(pre.test("manager"));
System.out.println(pre.test("admin"));

Consumer<String> con = (String message) -> {
   System.out.println("要發送的消息:" + message);
   System.out.println("消息發送完成");
};
con.accept("hello 慕課網的學員們..");
con.accept("imooc lambda expression.");

Function<String, Integer> fun = (String gender) -> {
   return "male".equals(gender)?1:0;
};
System.out.println(fun.apply("male"));
System.out.println(fun.apply("female"));

Supplier<String> sup = () -> {
   return UUID.randomUUID().toString();
};
System.out.println(sup.get());
System.out.println(sup.get());
System.out.println(sup.get());

UnaryOperator<String> uo = (String img)-> {
   img += "[100x200]";
   return img;
};

System.out.println(uo.apply("原圖--"));

BinaryOperator<Integer> bo = (Integer i1, Integer i2) -> {
   return i1 > i2? i1: i2;
};

System.out.println(bo.apply(12, 13));

package imooclambda;

import com.imooc.IMessageFormat;
import com.imooc.IUserCredential;
import com.imooc.impl.UserCredentialImpl;
import com.imooc.impl.impl.MessageFormatImpl;
import java.util.Random;
import java.util.UUID;
import java.util.function.*;

/**
 * Hello world!
 *
 * 需求改動:
 *  所有的用戶驗證,可以同時獲取用戶的驗證信息[是否認證成功|成功~返回用戶|null]
 *
 *  Lambda表達式 基本語法
 */
public class App 
{
    String welcome = "慕課網歡迎您.";
    public static void main( String[] args ) {
        // 1. lambda表達式的基本語法
        /*
            1)聲明:就是和lambda表達式綁定的接口類型
            2)參數:包含在一對圓括號中,和綁定的接口中的抽象方法中的參數個數及順序一致。
            3)操作符:->
            4)執行代碼塊:包含在一對大括號中,出現在操作符號的右側

            [接口聲明] = (參數) -> {執行代碼塊};
         */
       ILambda1 i1 = () -> {
           System.out.println("hello imooc!");
           System.out.println("welcome to imooc!");
       };
       i1.test();

       ILambda1 i2 = () -> System.out.println("hello imooc");
       i2.test();

       ILambda2 i21 = (String n, int a) -> {
           System.out.println(n + "say: my year's old is " + a);
       };
       i21.test("jerry", 18);

       ILambda2 i22 = (n, a) -> {
           System.out.println(n + " 說:我今年" + a + "歲了.");
       };
       i22.test("tom", 22);

       ILambda3 i3 = (x, y) -> {
           int z = x + y;
           return z;
       };
       System.out.println(i3.test(11, 22));

       ILambda3 i31 = (x, y) -> x + y;
       System.out.println(i31.test(100, 200));

        /*
            1. lambda表達式,必須和接口進行綁定。
            2. lambda表達式的參數,可以附帶0個到n個參數,括號中的參數類型可以不用指定,jvm在運行時,會自動根據綁定的抽象方法中電參數進行推導。
            3. lambda表達式的返回值,如果代碼塊只有一行,並且沒有大括號,不用寫return關鍵字,單行代碼的執行結果,會自動返回。
                如果添加了大括號,或者有多行代碼,必須通過return關鍵字返回執行結果。
         */

    }

    // 沒有參數,沒有返回值的lambda表達式綁定的接口
    interface ILambda1{
        void test();
    }

    // 帶有參數,沒有返回值的lambda表達式
    interface ILambda2{
        void test(String name, int age);
    }

    // 帶有參數,帶有返回值的lambda表達式
    interface ILambda3 {
        int test(int x, int y);
    }
}

package imooclambda;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
 * FileName: imooclambda App2
 * <p>lambda表達式 變量捕獲</p>
 *
 * @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
 * @version 1.00
 */
public class App2 {
    String s1 = "全局變量";

    // 1. 匿名內部類型中對於變量的訪問
    public void testInnerClass() {
        String s2 = "局部變量";

        new Thread(new Runnable() {
            String s3 = "內部變量";
            @Override
            public void run() {
                // 訪問全局變量
//                System.out.println(this.s1);// this關鍵字~表示是當前內部類型的對象
                System.out.println(s1);

                System.out.println(s2);// 局部變量的訪問,~不能對局部變量進行數據的修改[final]
//                s2 = "hello";

                System.out.println(s3);
                System.out.println(this.s3);

            }
        }).start();
    }

    // 2. lambda表達式變量捕獲
    public void testLambda() {
        String s2 = "局部變量lambda";

        new Thread(() -> {
            String s3 = "內部變量lambda";

            // 訪問全局變量
            System.out.println(this.s1);// this關鍵字,表示的就是所屬方法所在類型的對象
            // 訪問局部變量
            System.out.println(s2);
//            s2 = "hello";// 不能進行數據修改,默認推導變量的修飾符:final
            System.out.println(s3);
            s3 = "labmda 內部變量直接修改";
            System.out.println(s3);
        }).start();
    }

    public static void main(String[] args) {
        App2 app = new App2();
//        app.testInnerClass();
        app.testLambda();

    }
}

package imooclambda;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
 * FileName: imooclambda App3
 * <p>lambda表達式類型檢查</p>
 *
 * @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
 * @version 1.00
 */
public class App3 {

    public static void test(MyInterface<String, List> inter) {
        List<String> list = inter.strategy("hello", new ArrayList());
        System.out.println(list);
    }

    public static void main(String[] args) {
        test(new MyInterface<String, List>() {
            @Override
            public List strategy(String s, List list) {
                list.add(s);
                return list;
            }
        });

        test((x, y) -> {
            y.add(x);
            return y;
//            x.add(y);
//            return x;
        });

        /*
        (x,y)->{..} --> test(param) --> param==MyInterface --> lambda表達式-> MyInterface類型
        這個就是對於lambda表達式的類型檢查,MyInterface接口就是lambda表達式的目標類型(target typing)

        (x,y)->{..} --> MyInterface.strategy(T r, R r)--> MyInterface<String, List> inter
            --> T==String R==List --> lambda--> (x, y) == strategy(T t , R r)--> x==T==String  y==R==List
            lambda表達式參數的類型檢查
         */

    }
}

@FunctionalInterface
interface MyInterface<T, R> {
    R strategy (T t, R r);
}

package imooclambda;

/**
 * Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
 * FileName: imooclambda App4
 * <p>方法重載對於lmabda表達式的影響</p>
 *
 * @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
 * @version 1.00
 */
public class App4 {

    interface Param1 {
        void outInfo(String info);
    }

    interface Param2 {
        void outInfo(String info);
    }

    // 定義重載的方法
    public void lambdaMethod(Param1 param) {
        param.outInfo("hello param1 imooc!");
    }
    public void lambdaMethod(Param2 param) {
        param.outInfo("hello param2 imooc");
    }

    public static void main(String[] args) {
        App4 app = new App4();

        app.lambdaMethod(new Param1() {
            @Override
            public void outInfo(String info) {
                System.out.println(info);
            }
        });

        app.lambdaMethod(new Param2() {
            @Override
            public void outInfo(String info) {
                System.out.println("------");
                System.out.println(info);
            }
        });

        /*
        lambda表達式存在類型檢查-> 自動推導lambda表達式的目標類型
        lambdaMethod() -> 方法 -> 重載方法
                -> Param1  函數式接口
                -> Param2  函數式接口
                調用方法-> 傳遞Lambda表達式-> 自動推導->
                    -> Param1 | Param2
         */
//        app.lambdaMethod( (String info) -> {
//            System.out.println(info);
//        });
    }
}

package com.imooc.test;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
 * FileName: com.imooc.test Test
 * <p>
 *     1. 靜態方法引用的使用
 *      類型名稱.方法名稱() --> 類型名稱::方法名稱
 *     2. 實例方法引用的使用
 *      創建類型對應的一個對象 --> 對象應用::實例方法名稱
 *     3. 構造方法引用的使用
 *      類型對象的構建過程 --> 類型名稱::new
 * </p>
 *
 * @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
 * @version 1.00
 */
public class Test {

    public static void main(String[] args) {
       // 存儲Person對象的列表
       List<Person> personList = new ArrayList<>();
       personList.add(new Person("tom", "男", 16));
       personList.add(new Person("jerry", "女", 15));
       personList.add(new Person("shuke", "男", 30));
       personList.add(new Person("beita", "女", 26));
       personList.add(new Person("damu", "男", 32));

       // 1. 匿名內部類實現方式
       Collections.sort(personList, new Comparator<Person>() {
           @Override
           public int compare(Person o1, Person o2) {
               return o1.getAge() - o2.getAge();
           }
       });
       System.out.println(personList);

       // 2. lambda表達式的實現方式
       Collections.sort(personList, (p1, p2) -> p1.getAge() - p2.getAge());

       // 3. 靜態方法引用
       Collections.sort(personList, Person::compareByAge);

       // 4. 實例方法引用
       PersonUtil pu = new PersonUtil();
       Collections.sort(personList, pu::compareByName);
       System.out.println("tom".hashCode());
       System.out.println("jerry".hashCode());
       System.out.println(personList);

       // 5. 構造方法引用:綁定函數式接口
       IPerson ip = Person::new;
       Person person = ip.initPerson("jerry", "男", 22);
       System.out.println(person);
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
   private String name;    // 姓名
   private String gender;  // 性別
   private int age;        // 年齡

   public static int compareByAge(Person p1, Person p2) {
       return p1.getAge() - p2.getAge();
   }
}

class PersonUtil {
   // 增加一個實例方法
   public int compareByName(Person p1, Person p2) {
       return p1.getName().hashCode() - p2.getName().hashCode();
   }
}

interface IPerson {
   // 抽象方法:通過指定類型的構造方法初始化對象數據
   Person initPerson(String name, String gender, int age);
}

package com.imooc.test;

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

/**
 * Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
 * FileName: com.test Test2
 * <p>Stream概述</p>
 *
 * @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
 * @version 1.00
 */
public class Test2 {
    public static void main(String[] args) {
        // 1. 添加測試數據:存儲多個賬號的列表
        List<String> accounts = new ArrayList<String>();
        accounts.add("tom");
        accounts.add("jerry");
        accounts.add("beita");
        accounts.add("shuke");
        accounts.add("damu");

        // 1.1. 業務要求:長度大於等於5的有效賬號
        for (String account : accounts) {
            if (account.length() >= 5) {
                System.out.println("有效賬號:"  + account);
            }
        }

        // 1.2. 迭代方式進行操作
        Iterator<String> it = accounts.iterator();
        while(it.hasNext()) {
            String account = it.next();
            if (account.length() >= 5) {
                System.out.println("it有效賬號:" + account);
            }
        }

        // 1.3. Stream結合lambda表達式,完成業務處理
        List validAccounts = accounts.stream().filter(s->s.length()>=5).collect(Collectors.toList());
        System.out.println(validAccounts);

    }
}

package com.imooc.test;

import java.io.BufferedReader;

/**
 * Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
 * FileName: com.imooc.test Test3
 * <p>Stream常見操作API介紹
 *  1. 聚合操作
 *
 *  2. stream的處理流程
 *      數據源
 *      數據轉換
 *      獲取結果
 *  3. 獲取Stream對象
 *      1. 從集合或者數組中獲取[**]
 *          Collection.stream(),如accounts.stream()
 *          Collection.parallelStream()
 *          Arrays.stream(T t)
 *      2. BufferReader
 *          BufferReader.lines()-> stream()
 *      3. 靜態工廠
 *          java.util.stream.IntStream.range()..
 *          java.nio.file.Files.walk()..
 *      4. 自定構建
 *          java.util.Spliterator
 *      5. 更多的方式..
 *          Random.ints()
 *          Pattern.splitAsStream()..
 *   4. 中間操作API{intermediate}
 *      操作結果是一個Stream,中間操作可以有一個或者多個連續的中間操作,需要注意的是,中間操作
 *          只記錄操作方式,不做具體執行,直到結束操作發生時,才做數據的最終執行。
 *          中間操作:就是業務邏輯處理。
 *      中間操作過程:無狀態:數據處理時,不受前置中間操作的影響。
 *                      map/filter/peek/parallel/sequential/unordered
 *                  有狀態:數據處理時,受到前置中間操作的影響。
 *                      distinct/sorted/limit/skip
 *   5. 終結操作|結束操作{Terminal}
 *      需要注意:一個Stream對象,只能有一個Terminal操作,這個操作一旦發生,就會真實處理數據,生成對應的處理結果。
 *      終結操作:非短路操作:當前的Stream對象必須處理完集合中所有 數據,才能得到處理結果。
 *                  forEach/forEachOrdered/toArray/reduce/collect/min/max/count/iterator
 *              短路操作:當前的Stream對象在處理過程中,一旦滿足某個條件,就可以得到結果。
 *                  anyMatch/allMatch/noneMatch/findFirst/findAny等
 *                  Short-circuiting,無限大的Stream-> 有限大的Stream。
 * </p>
 *
 * @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
 * @version 1.00
 */
public class Test3 {}

package com.imooc.test;

import java.util.*;
import java.util.stream.Stream;

/**
 * Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
 * FileName: com.imooc.text Test1
 * <p>集合元素的常見操作</p>
 *
 * @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
 * @version 1.00
 */
public class Test1 {

    public static void main(String[] args) {
        // 1. 批量數據 -> Stream對象
        // 多個數據
        Stream stream = Stream.of("admin", "tom", "damu");

        // 數組
        String [] strArrays = new String[] {"xueqi", "biyao"};
        Stream stream2 = Arrays.stream(strArrays);

        // 列表
        List<String> list = new ArrayList<>();
        list.add("少林");
        list.add("武當");
        list.add("青城");
        list.add("崆峒");
        list.add("峨眉");
        Stream stream3 = list.stream();

        // 集合
        Set<String> set = new HashSet<>();
        set.add("少林羅漢拳");
        set.add("武當長拳");
        set.add("青城劍法");
        Stream stream4 = set.stream();

        // Map
        Map<String, Integer> map = new HashMap<>();
        map.put("tom", 1000);
        map.put("jerry", 1200);
        map.put("shuke", 1000);
        Stream stream5 = map.entrySet().stream();

        // 2. Stream對象對於基本數據類型的功能封裝
        // int / long / double
//        IntStream.of(new int[] {10, 20, 30}).forEach(System.out::println);
//        IntStream.range(1, 5).forEach(System.out::println);
//        IntStream.rangeClosed(1, 5).forEach(System.out::println);

        // 3. Stream對象 --> 轉換得到指定的數據類型
        // 數組
//        Object [] objx = stream.toArray(String[]::new);

        // 字符串
//        String str = stream.collect(Collectors.joining()).toString();
//        System.out.println(str);

        // 列表
//        List<String> listx = (List<String>) stream.collect(Collectors.toList());
//        System.out.println(listx);

        // 集合
//        Set<String> setx = (Set<String>) stream.collect(Collectors.toSet());
//        System.out.println(setx);

        // Map
//        Map<String, String> mapx = (Map<String, String>) stream.collect(Collectors.toMap(x->x, y->"value:"+y));
//        System.out.println(mapx);

        // 4. Stream中常見的API操作
        List<String> accountList = new ArrayList<>();
        accountList.add("xongjiang");
        accountList.add("lujunyi");
        accountList.add("wuyong");
        accountList.add("linchong");
        accountList.add("luzhishen");
        accountList.add("likui");
        accountList.add("wusong");

        // map() 中間操作,map()方法接收一個Functional接口
//        accountList = accountList.stream().map(x->"梁山好漢:" + x).collect(Collectors.toList());

        // filter() 添加過濾條件,過濾符合條件的用戶
//        accountList = accountList.stream().filter(x-> x.length() > 5).collect(Collectors.toList());

        // forEach 增強型循環
//        accountList.forEach(x-> System.out.println("forEach->" + x));
//        accountList.forEach(x-> System.out.println("forEach->" + x));
//        accountList.forEach(x-> System.out.println("forEach->" + x));

        // peek() 中間操作,迭代數據完成數據的依次處理過程
//        accountList.stream()
//                .peek(x -> System.out.println("peek 1: " + x))
//                .peek(x -> System.out.println("peek 2:" + x))
//                .forEach(System.out::println);

//        accountList.forEach(System.out::println);

        // Stream中對於數字運算的支持
        List<Integer> intList = new ArrayList<>();
        intList.add(20);
        intList.add(19);
        intList.add(7);
        intList.add(8);
        intList.add(86);
        intList.add(11);
        intList.add(3);
        intList.add(20);

        // skip() 中間操作,有狀態,跳過部分數據
//        intList.stream().skip(3).forEach(System.out::println);

        // limit() 中間操作,有狀態,限制輸出數據量
//        intList.stream().skip(3).limit(2).forEach(System.out::println);

        // distinct() 中間操作,有狀態,剔除重複的數據
//        intList.stream().distinct().forEach(System.out::println);

        // sorted() 中間操作,有狀態,排序

        // max() 獲取最大值
        Optional optional = intList.stream().max((x, y)-> x-y);
        System.out.println(optional.get());
        
        // min() 獲取最小值 類似 max()
        // ……

        // reduce() 合併處理數據
        Optional optional2 = intList.stream().reduce((sum, x)-> sum + x);
        System.out.println(optional2.get());
    }
}

 

package com.imooc.performance;

import java.util.*;

public class Test {

    public static void main(String[] args) {

        Random random = new Random();
        // 1. 基本數據類型:整數
//        List<Integer> integerList = new ArrayList<Integer>();
//
//        for(int i = 0; i < 1000000; i++) {
//            integerList.add(random.nextInt(Integer.MAX_VALUE));
//        }
//
//        // 1) stream
//        testStream(integerList);
//        // 2) parallelStream
//        testParallelStream(integerList);
//        // 3) 普通for
//        testForloop(integerList);
//        // 4) 增強型for
//        testStrongForloop(integerList);
//        // 5) 迭代器
//        testIterator(integerList);

        // 2. 複雜數據類型:對象
        List<Product> productList = new ArrayList<>();
        for(int i = 0; i < 1000000; i++) {
            productList.add(new Product("pro" + i, i, random.nextInt(Integer.MAX_VALUE)));
        }

        // 調用執行
        testProductStream(productList);
        testProductParallelStream(productList);
        testProductForloop(productList);
        testProductStrongForloop(productList);
        testProductIterator(productList);

    }

    public static void testStream(List<Integer> list) {
        long start = System.currentTimeMillis();

        Optional optional = list.stream().max(Integer::compare);
        System.out.println(optional.get());

        long end = System.currentTimeMillis();
        System.out.println("testStream:" + (end - start) + "ms");
    }

    public static void testParallelStream(List<Integer> list) {
        long start = System.currentTimeMillis();

        Optional optional = list.parallelStream().max(Integer::compare);
        System.out.println(optional.get());

        long end = System.currentTimeMillis();
        System.out.println("testParallelStream:" + (end - start) + "ms");
    }

    public static void testForloop(List<Integer> list) {
        long start = System.currentTimeMillis();

        int max = Integer.MIN_VALUE;
        for(int i = 0; i < list.size(); i++) {
            int current = list.get(i);
            if (current > max) {
                max = current;
            }
        }
        System.out.println(max);

        long end = System.currentTimeMillis();
        System.out.println("testForloop:" + (end - start) + "ms");
    }

    public static void testStrongForloop(List<Integer> list) {
        long start = System.currentTimeMillis();

        int max = Integer.MIN_VALUE;
        for (Integer integer : list) {
            if(integer > max) {
                max = integer;
            }
        }
        System.out.println(max);

        long end = System.currentTimeMillis();
        System.out.println("testStrongForloop:" + (end - start) + "ms");
    }

    public static void testIterator(List<Integer> list) {
        long start = System.currentTimeMillis();

        Iterator<Integer> it = list.iterator();
        int max = it.next();

        while(it.hasNext()) {
            int current = it.next();
            if(current > max) {
                max = current;
            }
        }
        System.out.println(max);

        long end = System.currentTimeMillis();
        System.out.println("testIterator:" + (end - start) + "ms");
    }


    public static void testProductStream(List<Product> list) {
        long start = System.currentTimeMillis();

        Optional optional = list.stream().max((p1, p2)-> p1.hot - p2.hot);
        System.out.println(optional.get());

        long end = System.currentTimeMillis();
        System.out.println("testProductStream:" + (end - start) + "ms");
    }

    public static void testProductParallelStream(List<Product> list) {
        long start = System.currentTimeMillis();

        Optional optional = list.stream().max((p1, p2)-> p1.hot - p2.hot);
        System.out.println(optional.get());

        long end = System.currentTimeMillis();
        System.out.println("testProductParallelStream:" + (end - start) + "ms");
    }

    public static void testProductForloop(List<Product> list) {
        long start = System.currentTimeMillis();

        Product maxHot = list.get(0);
        for(int i = 0; i < list.size(); i++) {
            Product current = list.get(i);
            if (current.hot > maxHot.hot) {
                maxHot = current;
            }
        }
        System.out.println(maxHot);

        long end = System.currentTimeMillis();
        System.out.println("testProductForloop:" + (end - start) + "ms");
    }

    public static void testProductStrongForloop(List<Product> list) {
        long start = System.currentTimeMillis();

        Product maxHot = list.get(0);
        for (Product product : list) {
            if(product.hot > maxHot.hot) {
                maxHot = product;
            }
        }
        System.out.println(maxHot);

        long end = System.currentTimeMillis();
        System.out.println("testProductStrongForloop:" + (end - start) + "ms");
    }

    public static void testProductIterator(List<Product> list) {
        long start = System.currentTimeMillis();

        Iterator<Product> it = list.iterator();
        Product maxHot = it.next();

        while(it.hasNext()) {
            Product current = it.next();
            if (current.hot > maxHot.hot) {
                maxHot = current;
            }
        }
        System.out.println(maxHot);

        long end = System.currentTimeMillis();
        System.out.println("testProductIterator:" + (end - start) + "ms");
    }

}

class Product {
    String name;    // 名稱
    Integer stock;  // 庫存
    Integer hot;    // 熱度

    public Product(String name, Integer stock, Integer hot) {
        this.name = name;
        this.stock = stock;
        this.hot = hot;
    }
}

package com.imooc.performance;

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

public class Test2 {

    public static void main(String[] args) {
        // 整數列表
        List<Integer> lists = new ArrayList<Integer>();
        
        // 增加數據
        for (int i = 0; i < 1000; i++){
            lists.add(i);
        }

        // 串行Stream
        List<Integer> list2 = new ArrayList<>();
        lists.stream().forEach(x->list2.add(x));
        System.out.println(lists.size());
        System.out.println(list2.size());
        
        // 並行Stream
        List<Integer> list3 = new ArrayList<>();
        lists.parallelStream().forEach(x-> list3.add(x));
        System.out.println(list3.size());

        List<Integer> list4 = lists.parallelStream().collect(Collectors.toList());
        System.out.println(list4.size());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章