欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

吊打Java面試官之Lambda表達(dá)式 Stream API

 更新時(shí)間:2021年09月06日 17:35:27   作者:維斯布魯克.猩猩  
這篇文章主要介紹了吊打Java之jdk8的新特性包括Lambda表達(dá)式、函數(shù)式接口、Stream API全面刨析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、jdk8新特性簡(jiǎn)介

二、Lambda表達(dá)式

簡(jiǎn)單理解一下Lambda表達(dá)式

public class LambdaTest {
    @Test
    public void test1(){
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("我愛北京天安門");
            }
        };
        r1.run();
        System.out.println("******************************************");
        Runnable r2 = () -> System.out.println("我愛北京故宮");
        r2.run();
    }
    @Test
    public void test2(){
        Comparator<Integer> com1 = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1,o2);
            }
        };
        int compare1 = com1.compare(12,21);
        System.out.println(compare1);
        System.out.println("**********************************");
        //Lambda表達(dá)式的寫法
        Comparator<Integer> com2 = (o1,o2) -> Integer.compare(o1,o2);
        int compare2 = com2 .compare(32,21);
        System.out.println(compare2);
        System.out.println("************************************");
        //方法引用
        Comparator<Integer> com3 = Integer :: compare;
        int compare3 = com3.compare(32,21);
        System.out.println(compare2);
    }

Lambda表達(dá)式的使用

1.舉例:(o1,o2) -> Integer.compare(o1,o2);
2.格式:
->:lambda操作符 或 箭頭操作符
->:左邊:lambda形參列表 (其實(shí)就是接口中的抽象方法的形參列表)
->:右邊:lambda體 (其實(shí)就是重寫的抽象方法的方法體)
3.Lambda表達(dá)式的使用:(分為6種情況介紹)
總結(jié):(重點(diǎn)看這個(gè))
->左邊:lambda形參列表的參數(shù)類型可以省略(類型推斷);如果lambda形參列表只有一個(gè)參數(shù),其一對(duì)()也可以省略
->右邊:lambda體應(yīng)該使用一對(duì){}包裹;如果lambda體只有一條執(zhí)行語句(可能時(shí)return語句),可以省略這一對(duì){}和return關(guān)鍵字
4.Lambda表達(dá)式的本質(zhì):作為函數(shù)式接口的實(shí)例
5.如果一個(gè)接口中,只聲明了一個(gè)抽象方法,則此接口就稱為函數(shù)式接口

public class LambdaTest1 {
    //語法格式一:無參,無返回值
    @Test
    public void test1(){
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("我愛北京天安門");
            }
        };
        r1.run();
        System.out.println("******************************************");
        Runnable r2 = () -> {
            System.out.println("我愛北京故宮");
        };
 
        r2.run();
    }
    //語法格式二:Lambda需要一個(gè)參數(shù),但是沒有返回值。
    @Test
    public void test2(){
        Consumer<String> con = new Consumer<String>() {
 
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
        con.accept("謊言和誓言的區(qū)別什么?");
        System.out.println("**********************************");
        Consumer<String>con1 = (String s) -> {
            System.out.println(s);
        };
        con1.accept("一個(gè)是聽得人當(dāng)真了,一個(gè)是說的人當(dāng)真了");
    }
    //語法格式三:數(shù)據(jù)類型可以省略,因?yàn)榭捎删幾g器推斷得出,稱為"類型推斷"
    @Test
    public void test3(){
        Consumer<String> con1 = (String s) -> {
            System.out.println(s);
        };
        con1.accept("一個(gè)是聽的人當(dāng)真了,一個(gè)是說的人當(dāng)真了");
        System.out.println("****************************");
        Consumer<String> con2 = (s) -> {
            System.out.println(s);
        };
        con2.accept("一個(gè)是聽的人當(dāng)真了,一個(gè)是說的人當(dāng)真了");
    }
    @Test
    public void test4(){
        ArrayList<String> objects = new ArrayList<>();//類型推斷(泛型)
        int[] arr = {1,2,3};//類型推斷(int[] arr = new int[]{1,2,3};)
    }
    //語法格式四:Lambda若只需要一個(gè)參數(shù)時(shí),參數(shù)的小括號(hào)可以省略
    @Test
    public void test5(){
        Consumer<String> con1 = (s) -> {
            System.out.println(s);
        };
        con1.accept("一個(gè)是聽的人當(dāng)真了,一個(gè)是說的人當(dāng)真了");
        System.out.println("****************************");
        Consumer<String> con2 = s -> {
            System.out.println(s);
        };
        con2.accept("一個(gè)是聽的人當(dāng)真了,一個(gè)是說的人當(dāng)真了");
    }
    //語法格式五:Lambda需要兩個(gè)或兩個(gè)以上的參數(shù),多條執(zhí)行語句,并且可以有返回值
    @Test
    public void test6(){
        Comparator<Integer> com1 = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                System.out.println(o1);
                System.out.println(o2);
                return Integer.compare(o1,o2);
            }
        };
        System.out.println(com1.compare(12,21));
        System.out.println("*******************************");
        Comparator<Integer> com2 = (o1,o2) -> {
            System.out.println(o1);
            System.out.println(o2);
            return o1.compareTo(o2);
        };
        System.out.println(com2.compare(12,6));
    }
    //語法格式六:當(dāng)Lambda體只有一條語句時(shí),return與大括號(hào)若有,都可以省略
    @Test
    public void test7(){
        Comparator<Integer> com1 = (o1,o2) ->{
            return o1.compareTo(o2);
        };
        System.out.println(com1.compare(12,6));
        System.out.println("******************************");
        Comparator<Integer> com2 = (o1,o2) -> o1.compareTo(o2);
        System.out.println(com2.compare(12,21));
    }
    @Test
    public void test8(){
        Consumer<String> con1 = s -> {
            System.out.println(s);
        };
        con1.accept("一個(gè)是聽的人當(dāng)真了,一個(gè)是說的人當(dāng)真了");
        System.out.println("*********************************");
 
        Consumer<String> con2 = s -> System.out.println(s);
        con2.accept("一個(gè)是聽的人當(dāng)真了,一個(gè)是說的人當(dāng)真了");
    }
}

三、函數(shù)式接口

1.什么是函數(shù)式接口

2.如何理解函數(shù)式接口

總結(jié):只有函數(shù)式接口在實(shí)例化的時(shí)候,才可以用上Lambda表達(dá)式!?。。。。。。?!

3.Java內(nèi)置四大核心函數(shù)式接口

java內(nèi)置的4大核心函數(shù)式接口

消費(fèi)型接口Consumer<T>       void accept(T t)
供給型接口Supplier<T>       T get()
函數(shù)式接口Function<T,R>     R apply(T t)
斷定型接口Predicate<T>      boolean test(T t)

 public class LambdaTest2 {
    @Test
    public void test1(){
        happyTime(500, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("學(xué)習(xí)太累了,去天上人間買了瓶礦泉水,價(jià)格為:" + aDouble);
            }
        });
        System.out.println("*************************************");
        happyTime(400,money -> System.out.println("學(xué)習(xí)太累了,去天上人間喝兩口礦泉水,價(jià)格為:" + money));
    }
    public void happyTime(double money, Consumer<Double> con){
        con.accept(money);
    }
    @Test
    public void test2(){
        List<String> list = Arrays.asList("北京", "南京", "天津", "東京", "西京", "普京");
        List<String> filterStrs = filterString(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("京");
            }
        });
        System.out.println(filterStrs);
        List<String> filterStrs1 = filterString(list, s -> s.contains("京"));
        System.out.println(filterStrs1);
    }
    //根據(jù)給定的規(guī)則,過濾集合中的字符串,此規(guī)則由Predicate的方法決定
    public List<String> filterString(List<String> list,Predicate<String> pre){
        ArrayList<String> filterList = new ArrayList<>();
        for(String s : list){
            if(pre.test(s)){
                filterList.add(s);
            }
        }
        return filterList;
    }

四、方法引用與構(gòu)造器引用

方法引用

1.使用情境:當(dāng)要傳遞給Lambda體的操作,已經(jīng)有實(shí)現(xiàn)的方法了,可以使用方法引用!
2.方法引用,本質(zhì)上就是Lambda表達(dá)式,而Lambda表達(dá)式作為函數(shù)式接口的實(shí)例,所以,方法引用,也是函數(shù)式接口的實(shí)例。
3.使用格式:類(或?qū)ο? :: 方法名
4.具體分為如下的三種情況:
情況1 對(duì)象 :: 非靜態(tài)方法
情況2 類 :: 靜態(tài)方法
情況3 類 :: 非靜態(tài)方法
5.方法引用使用的要求:

> 要求接口中的抽象方法的形參列表和返回值類型與方法引用的方法的形參列表和返回值類型相同!(針對(duì)于情況1、2)

> 當(dāng)函數(shù)式接口方法的第一個(gè)參數(shù)是需要引用方法的調(diào)用者,并且第二個(gè)參數(shù)是需要引用方法的參數(shù)(或無參數(shù))時(shí):ClassName::methodName(針對(duì)于情況3)

6.使用建議:

如果給函數(shù)式接口提供實(shí)例,恰好滿足方法引用的使用情境,大家就可以考慮使用方法引用給函數(shù)式接口提供實(shí)例。如果大家不熟悉方法引用,那么還可以使用lambda表達(dá)式。

 情況一:對(duì)象 :: 實(shí)例方法
    Consumer中的void accept(T t)
    PrintStream中的void println(T t)
    @Test
    public void test1(){
        Consumer<String> con1 = str -> System.out.println(str);
        con1.accept("北京");
        System.out.println("**************************");
        PrintStream ps = System.out;
        Consumer<String> con2 = ps :: println;
        con2.accept("beijing");
    }
    //Supplier中的T get()
    //Employee中的String getName()
    @Test
    public void test2(){
        Employee emp = new Employee(1001, "Tom", 23, 5600);
        Supplier<String> sup1 = () -> emp.getName();
        System.out.println(sup1.get());
        System.out.println("****************************");
        Supplier<String> sup2 = emp :: getName;
        System.out.println(sup2.get());
    }
    //情況二:類 :: 靜態(tài)方法
    //Comparator中的int compare(T t1,T t2)
    //Integer中的int compare(T t1,T t2)
    @Test
    public void test3(){
        Comparator<Integer> com1 = (t1, t2) -> Integer.compare(t1,t2);
        System.out.println(com1.compare(12,21));
        System.out.println("*********************************");
        Comparator<Integer> com2 = Integer :: compare;
        System.out.println(com2.compare(12,3));
    }
    //Function中的R apply(T t)
    //Math中的Long round(Double d)
    @Test
    public void test4(){
        Function<Double, Long> func = new Function<Double, Long>() {
            @Override
            public Long apply(Double d) {
                return Math.round(d);
            }
        };
        System.out.println("************************************");
        Function<Double,Long> func1 = d -> Math.round(d);
        System.out.println(func1.apply(12.3));
 
        System.out.println("*****************************");
        Function<Double,Long> func2 = Math :: round;
        System.out.println(func2.apply(12.6));
    }
    //情況三:類 :: 實(shí)例方法(有難度)
    //String 中的 int t1.compareTo(t2)
    @Test
    public void test5(){
        Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
        System.out.println(com1.compare("abc","abd"));
        System.out.println("*****************************");
        Comparator<String> com2 = String :: compareTo;
        System.out.println(com2.compare("abd","abm"));
    }
    //BiPredicate中的boolean test(T t1,T t2);
    //String中的boolean t1.equals(t2)
    @Test
    public void test6(){
        BiPredicate<String,String> pre1 = (s1, s2) -> s1.equals(s2);
        System.out.println(pre1.test("abc","abc"));
        System.out.println("**************************");
        BiPredicate<String,String> pre2 = String :: equals;
        System.out.println(pre1.test("abc","abd"));
    }
    //Function中的R apply(T t)
    //Employee中的String getName();
    @Test
    public void test7(){
        Employee employee = new Employee(1001, "Jerry", 23, 6000);
        Function<Employee,String> func1 = e -> e.getName();
        System.out.println(func1.apply(employee));
        System.out.println("****************************");
        Function<Employee,String> func2 = Employee :: getName;
        System.out.println(func2.apply(employee));
    }

構(gòu)造器引用和數(shù)組引用

一、構(gòu)造器引用
和方法引用類似,函數(shù)式接口的抽象方法的形參列表構(gòu)造器的形參列表一致。
抽象方法的返回值類型即為構(gòu)造器所屬的類的類型
二、數(shù)組引用
大家可以把數(shù)組看作是一個(gè)特殊的類,則寫法與構(gòu)造器引用一致。

構(gòu)造器引用
    Supplier中的T get()
    Employee的空參構(gòu)造器:Employee()
    @Test
    public void test1(){
        Supplier<Employee> sup = new Supplier<Employee>(){
            @Override
            public Employee get(){
                return new Employee();
            }
        };
        System.out.println("****************************");
        Supplier<Employee> sup1 = () -> new Employee();
        System.out.println(sup1.get());
        System.out.println("***********************************");
        Supplier<Employee> sup2 = Employee :: new;
        System.out.println(sup2.get());
    }
    //Function中的R apply(T t)
    @Test
    public void test2(){
        Function<Integer,Employee> func1 = id -> new Employee(id);
        Employee employee = func1.apply(1001);
        System.out.println(employee);
        System.out.println("********************************");
        Function<Integer,Employee> func2 = Employee :: new;
        Employee employee1 = func2.apply(1002);
        System.out.println(employee1);
    }
    //BiFunction中的R apply(T t,U u)
    @Test
    public void test3(){
        BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id,name);
        System.out.println(func1.apply(1001,"Tom"));
        System.out.println("**********************************");
        BiFunction<Integer,String,Employee> func2 = Employee :: new;
        System.out.println(func2.apply(1002,"Tom"));
    }
    //數(shù)組引用
    //Function中的R apply(T t)
    @Test
    public void test4(){
        Function<Integer,String[]> func1 = length -> new String[length];
        String[] arr1 = func1.apply(5);
        System.out.println(Arrays.toString(arr1));
        System.out.println("************************");
        Function<Integer,String[]> func2 = String[] :: new;
        String[] arr2 = func2.apply(10);
        System.out.println(Arrays.toString(arr2));
    }

五、Stream API

1.Stream API的說明

2.為什么要使用Stream API

1.Stream關(guān)注的是對(duì)數(shù)據(jù)的運(yùn)算,與CPU打交道
集合關(guān)注的是數(shù)據(jù)的存儲(chǔ),與內(nèi)存打交道
2.
A.Stream 自己不會(huì)存儲(chǔ)元素。
B.Stream 不會(huì)改變?cè)磳?duì)象。相反,他們會(huì)返回一個(gè)持有結(jié)果的型Stream
C.Stream 操作是延遲執(zhí)行的。這意味著他們會(huì)等到需要結(jié)果的時(shí)候才執(zhí)行
3.Stream 執(zhí)行流程
A.Stream的實(shí)例化
B.一系列的中間操作(過濾、映射、...)
C.終止操作

4.說明:
4.1 一個(gè)中間操作鏈,對(duì)數(shù)據(jù)源的數(shù)據(jù)進(jìn)行處理
4.2 一旦執(zhí)行終止操作,就執(zhí)行中間操作鏈,并產(chǎn)生結(jié)果。之后,不會(huì)再被使用

3.創(chuàng)建Stream的四種方式

//創(chuàng)建Stream方式一:通過集合
    @Test
    public void test1(){
        List<Employee>employees = EmployeeData.getEmployees();
//        default Stream<E> stream(): 返回一個(gè)順序流
        Stream<Employee> stream = employees.stream();
//        default Stream<E> parallelStream(): 返回一個(gè)并行流
        Stream<Employee> parallelStream = employees.parallelStream();
    }
    //創(chuàng)建Stream方式二:通過數(shù)組
    @Test
    public void test2(){
        int[] arr = new int[]{1,2,3,4,5,6};
        //調(diào)用Arrays類的static <T> stream(T[] array):返回一個(gè)流
        IntStream stream = Arrays.stream(arr);
        Employee e1 = new Employee(1001,"Tom");
        Employee e2 = new Employee(1001,"Jerry");
        Employee[] arr1 = new Employee[]{e1,e2};
        Stream<Employee> stream1 = Arrays.stream(arr1);
    }
    //創(chuàng)建Stream方式三:通過Stream的of()
    @Test
    public void test3(){
        Steram<Integer> stream = Stream.of(1,2,3,4,5,6);
    }
    //創(chuàng)建Stream方式四:創(chuàng)建無限流(用的少)
    @Test
    public void test4(){
        //迭代
//        public static<T> Stream<T> iterate(final T seed,final UnaryOperator<T> f)
        //遍歷前10個(gè)偶數(shù)
        Stream.iterate(0,t -> t + 2).limit(10).forEach(System.out :: println);
        //生成
//        public static<T> Stream<T> generate(Supplier<T> s)
        Stream.generate(Math::random).limit(10).forEach(System.out::println);
    }

4.Stream的中間操作及其測(cè)試

    @Test
    public void test1(){
        List<Employee> list = EmployeeData.getEmployees();
//        filter(Predicate p)--接收Lambda,從流中排除某些元素
        Stream<Employee> stream = list.stream();
        //練習(xí):查詢員工表中薪資大于7000的員工信息
        stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);
        System.out.println();
//      limit(n)--截?cái)嗔?,使?元素不超過給定數(shù)量
        list.stream().limit(3).forEach(System.out::println);
        System.out.println();
//        skip(n) -- 跳過元素,返回一個(gè)扔掉了前n個(gè)元素的流。若流中元素不足n個(gè),則返回一個(gè)空流。與limit(n)互補(bǔ)
        list.stream().skip(3).forEach(System.out::println);
//        distinct()--篩選,通過流所生成元素的hashCode()和equals()去除重復(fù)元素
        list.add(new Employee(1010,"劉強(qiáng)東",40,8000));
        list.add(new Employee(1010,"劉強(qiáng)東",40,8000));
        list.add(new Employee(1010,"劉強(qiáng)東",40,8000));
        list.add(new Employee(1010,"劉強(qiáng)東",40,8000));
        list.add(new Employee(1010,"劉強(qiáng)東",40,8000));
        list.stream().distinct().forEach(System.out::println);
    }
    //映射
    @Test
    public void test2(){
//        map(Function f)--接收一個(gè)函數(shù)作為參數(shù),將元素轉(zhuǎn)換成其他形式或提取信息,該函數(shù)
        List<String> list = Arrays.asList("aa","bb","cc","dd");
        list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);
//        練習(xí)1:獲取員工姓名長(zhǎng)度大于3的員工的姓名。
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<String> namesStream = employees.stream().map(employee::getName);
        namesStream.filter(name -> name.length() > 3).forEach(System.out::println);
//        練習(xí)2
        Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest1::fromStringToStream);
        streamStream.forEach(s ->{
            s.forEach(System.out::println);
        });
        System.out.println();
//        flatMap(Function f)--接受一個(gè)函數(shù)作為參數(shù),將流中的每個(gè)值都換成另一個(gè)流,然后
        Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);
        characterStream.forEach(System.out::println);
    }
    //將多個(gè)字符串中的多個(gè)字符構(gòu)成的集合轉(zhuǎn)換為對(duì)應(yīng)的Stream的實(shí)例
    public static Stream<Character> fromStringToStream(String str){
        ArrayList<Character> list = new ArrayList<>();
        for(Character c : str.toCharArray()){
            list.add(c);
        }
        return list.stream();
    }
    //幫助理解Stream映射的集合例子
    @Test
    public void test3(){
        ArrayList list1 = new ArrayList();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        ArrayList list2 = new ArrayList();
        list2.add(4);
        list2.add(5);
        list2.add(6);
//        list1.add(list2);
        list1.addAll(list2);
        System.out.println(list1);
    }
    @Test
    public void test4(){
//        sorted()--自然排序
        List<Integer> list = Arrays.asList(12,43,65,34,87,0,-98,7);
        list.stream().sorted().forEach(System.out::println);
        //拋異常,原因:Employee沒有實(shí)現(xiàn)Comparable接口
        List<Employee> employees = EmployeeData.getEmployees();
        employees.stream().sorted((e1,e2) ->{
            int ageValue = Integer.compare(e1.getAge(),e2.getAge());
            if(ageValue != 0){
                return ageValue;
            }else{
                return Double.compare(e1.getSalary(),e2.getSalary());
            }
        }).forEach(System.out::println);
    }

5.Stream的終止操作及其測(cè)試

Collector需要使用Collectors提供實(shí)例。

    @Test
    public void test1(){
        List<Employee> employees = EmployeeData.getEmployees();
//        allMatch(Predicate p)--檢查是否匹配所有元素
//        練習(xí):是否所有的員工的年齡都大于18
        boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
        System.out.println(allMatch);
//        anyMatch(Predicate p)--檢查是否至少匹配一個(gè)元素
//        練習(xí):是否存在員工的工資大于10000
        boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);
        System.out.println(anyMatch);
//        noneMatch(Predicate p)--檢查是否沒有匹配的元素
//        練習(xí):是否存在員工姓"雷"
        boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startWith("雷"));
        System.out.println(noneMatch);
//        findFirst--返回第一個(gè)元素
        Optional<Employee> employee = employees.stream().findFist();
        System.out.println(employee);
//        findAny--返回當(dāng)前流中的任意元素
        Optional<Employee> employees = employees.parallelStream().findAny();
        System.out.println(employee1);
 
    }
    @Test
    public void test2(){
//        count--返回流中元素的總個(gè)數(shù)
        long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
        System.out.println(count);
//        max(Comparator c)--返回流中最大值
//        練習(xí):返回最高的工資:
        Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
        Optional<Double> maxSalary = salaryStream.max(Double::compare);
        System.out.println(maxSalary);
//        min(Comparator c)--返回流中最小值
//        練習(xí):返回最低工資的員工
        Optional<Employee> employee = employees.stream().min((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()));
        System.out.println(employee);
//        forEach(Consumer c)--內(nèi)部迭代
        employees.stream().forEach(System.out::println);
        employees.forEach(System.out::println);
    }
    //歸約
    @Test
    public void test3(){
//        reduce(T identity,BinaryOperator)--可以將流中元素反復(fù)結(jié)合起來,得到一個(gè)值,返回T
//        練習(xí)1:計(jì)算1-10的自然數(shù)的和
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        Integer sum = list.stream().reduce(0,Itneger::sum);
        System.out.println(sum);
//        reduce(BinaryOperator)--可以將流中元素反復(fù)結(jié)合起來,得到一個(gè)值。返回Optional(T)
//        練習(xí)2:計(jì)算公司所有員工工資的總和
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
        Optional<Double> sumMoney = salaryStream.reduce((d1, d2) -> d1 + d2);
        System.out.println(sumMoney);
    }
    //3-收集
    @Test
    public void test4(){
//        collect(Collector c)--將流轉(zhuǎn)換為其他形式。接受一個(gè)Collector接口的實(shí)現(xiàn),用于給Stream中元素做匯總的方法
//        練習(xí)1:查找工資大于6000的員工,結(jié)果返回一個(gè)List或Set
        List<Employee> employees = EmployeeData.getEmployees();
        List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
        employeeList.forEach(System.out::println);
        System.out.println();
        Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
        employeeSet.forEach(System.out::println);
    }

六、Optional類的使用

Optional類的重要意義:

Optional類:為了在程序中避免出現(xiàn)空指針異常而創(chuàng)建的
常用的方法:ofNullable(T t)
orElse(T t)

 /*
    Optional.of(T t):創(chuàng)建一個(gè)Optional 實(shí)例,t必須非空
    Optional.empty():創(chuàng)建一個(gè)空的Optional實(shí)例
    Optional.ofNullable(T t):t可以為null
     */
    @Test
    public void test1(){
        Girl girl = new Girl();
        girl = null;
        //of(T t):保證t是非空的
        Optional<Girl> optionalGirl = Optional.of(girl);
    }
    @Test
    public void test2(){
        Girl girl = new Girl();
//        //ofNullable(T t):t可以為null
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);
        System.out.println(optionalGirl);
        //orElse(T t1):如果當(dāng)前的Optional內(nèi)部封裝的t是非空的,則返回內(nèi)部的t.
        //入股偶內(nèi)部的t是空的,則返回orElse()方法中的參數(shù)t1.
        Girl girl1 = optionalGirl.orElse(new Girl("憨憨"));
        System.out.println(girl1);
    }
    public String getGirlName(Boy boy){
        return boy.getGirl().getName();
    }
    @Test
    public void test3(){
        Boy boy = new Boy();
        boy = null;
        String girlName = getGirlName(boy);
        System.out.println(girlName);
    }
    //優(yōu)化以后的getGirlName():
    public String getGirlName1(Boy boy){
        if(boy != null){
            Girl girl = boy.getGirl();
            if(girl != null){
                return girl.getName();
            }
        }
        return null;
    }
    @Test
    public void test4(){
        Boy boy = new Boy();
        boy = null;
        String girlName = getGirlName1(boy);
        System.out.println(girlName);//null
    }
    //使用Optional類的getGirlName()
    public String getGirlName2(Boy boy){
        Optional<Boy> boyOptional = Optional.ofNullable(boy);
        //此時(shí)的boy1一定非空
        Boy boy1 = boyOptional.orElse(new Boy(new Girl("漂亮妹妹")));
        Girl girl = boy1.getGirl();
        Optional<Girl> girlOptional = Optional.ofNullable(girl);
        //girl1 一定非空
        Girl girl1 = girlOptional.orElse(new Girl("古力娜扎"));
        return girl1.getName();
    }
    @Test
    public void test5(){
        Boy boy = null;
        String girlName = getGirlName2(boy);
        System.out.println(girlName);
    }

到此這篇關(guān)于吊打Java面試官之jdk8新特性全面刨析面試無憂的文章就介紹到這了,更多相關(guān)jdk8特性內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java如何實(shí)現(xiàn)樹的同構(gòu)?

    Java如何實(shí)現(xiàn)樹的同構(gòu)?

    今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識(shí),文章圍繞著Java如何實(shí)現(xiàn)樹的同構(gòu)展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • Java判斷絕對(duì)值的方法總結(jié)

    Java判斷絕對(duì)值的方法總結(jié)

    在本文中作者為大家分享了兩種Java判斷絕對(duì)值的方法,對(duì)此有興趣的朋友可以和小編一起學(xué)習(xí)下。
    2018-02-02
  • java編程實(shí)現(xiàn)獲取服務(wù)器IP地址及MAC地址的方法

    java編程實(shí)現(xiàn)獲取服務(wù)器IP地址及MAC地址的方法

    這篇文章主要介紹了java編程實(shí)現(xiàn)獲取機(jī)器IP地址及MAC地址的方法,實(shí)例分析了Java分別針對(duì)單網(wǎng)卡及多網(wǎng)卡的情況下獲取服務(wù)器IP地址與MAC地址的相關(guān)技巧,需要的朋友可以參考下
    2015-11-11
  • Gradle 創(chuàng)建Task的多種方法

    Gradle 創(chuàng)建Task的多種方法

    本文主要介紹了Gradle 創(chuàng)建Task的多種方法,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • 如何在IDEA Maven項(xiàng)目中導(dǎo)入本地jar包的步驟

    如何在IDEA Maven項(xiàng)目中導(dǎo)入本地jar包的步驟

    今天小編就為大家分享一篇關(guān)于IDEA Maven項(xiàng)目中導(dǎo)入本地jar包的步驟,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • Java任意長(zhǎng)度byte數(shù)組轉(zhuǎn)換為int數(shù)組的方法

    Java任意長(zhǎng)度byte數(shù)組轉(zhuǎn)換為int數(shù)組的方法

    這篇文章主要給大家介紹了關(guān)于Java任意長(zhǎng)度byte數(shù)組轉(zhuǎn)換為int數(shù)組的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • 實(shí)例詳解SpringMVC入門使用

    實(shí)例詳解SpringMVC入門使用

    大家好,本篇文章主要講的是實(shí)例詳解SpringMVC入門使用,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • 以用戶名注冊(cè)為例分析三種Action獲取數(shù)據(jù)的方式

    以用戶名注冊(cè)為例分析三種Action獲取數(shù)據(jù)的方式

    這篇文章主要介紹了以用戶名注冊(cè)為例分析三種Action獲取數(shù)據(jù)的方式的相關(guān)資料,需要的朋友可以參考下
    2016-03-03
  • Java線程活鎖的實(shí)現(xiàn)與死鎖等的區(qū)別

    Java線程活鎖的實(shí)現(xiàn)與死鎖等的區(qū)別

    活鎖是一種遞歸情況,其中兩個(gè)或更多線程將繼續(xù)重復(fù)特定的代碼邏輯,本文主要介紹了Java線程活鎖的實(shí)現(xiàn)與死鎖等的區(qū)別,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-04-04
  • SpringBoot集成mqtt的多模塊項(xiàng)目配置詳解

    SpringBoot集成mqtt的多模塊項(xiàng)目配置詳解

    這篇文章主要介紹了SpringBoot集成mqtt的多模塊項(xiàng)目配置詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04

最新評(píng)論