lambda表達式Stream流使用

#Lambda表達式

Lambda允許把函數作爲一個方法的參數(函數作爲參數傳遞進方法中)


#lambda表達式本質上就是一個匿名方法。比如下面的例子:

public int add(int x, int y) {
    return x + y;
}

轉成Lambda表達式後是這個樣子:

(int x, int y) -> x + y;

參數類型也可以省略,Java編譯器會根據上下文推斷出來:

(x, y) -> x + y; //返回兩數之和

或者

(x, y) -> { return x + y; } //顯式指明返回值

#java 8 in Action這本書裏面的描述:

A lambda expression can be understood as a concise representation of an anonymous function
that can be passed around: it doesn’t have a name, but it has a list of parameters, a body, a
return type, and also possibly a list of exceptions that can be thrown. That’s one big definition;

#格式:

(x, y) -> x + y;
-----------------
(x,y):參數列表
x+y  : body

#Lambda表達式用法實例:

package LambdaUse;

/**
 * @author zhangwenlong
 * @date 2019/8/25 15:17
 */
public class LambdaUse {

    public static void main(String[] args) {

        //匿名類實現
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello world");
            }
        };
        //Lambda方式實現
        Runnable r2 = ()-> System.out.println("Hello world");

        process(r1);
        process(r2);
        process(()-> System.out.println("Hello world"));
    }
    private  static void  process(Runnable r){
        r.run();
    }
}

輸出的結果:

Hello world
Hello world
Hello world

FunctionalInterface註解修飾的函數

#predicate的用法

package LambdaUse;

import java.applet.Applet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.LongPredicate;
import java.util.function.Predicate;

/**
 * @author zhangwenlong
 * @date 2019/8/25 15:30
 */
public class PredicateTest {

    //通過名字(Predicate實現)
    private static List<Apple> filterApple(List<Apple> list, Predicate<Apple> predicate){
            List<Apple> appleList = new ArrayList<>();
            for(Apple apple : list){
                if(predicate.test(apple)){
                    appleList.add(apple);
                }
            }
            return appleList;
    }
    //通過重量(LongPredicate實現)
    private static List<Apple> filterWeight(List<Apple> list, LongPredicate predicate){
        List<Apple> appleList = new ArrayList<>();
        for(Apple apple : list){
            if(predicate.test(apple.getWeight())){
                appleList.add(apple);
            }
        }
        return appleList;
    }

    public static void main(String[] args) {

        List<Apple> list = Arrays.asList(new Apple("蘋果",120),new Apple("香蕉",110));
        List<Apple> applelist = filterApple(list,apple -> apple.getName().equals("蘋果"));
        System.out.println(applelist);
        List<Apple> appleList = filterWeight(list, (x) -> x > 110);
        System.out.println(appleList);
    }
}


執行結果:

[Apple{name='蘋果', weight=120}]
[Apple{name='蘋果', weight=120}]

#Lambda表達式的方法推導

package LambdaUse;

import java.util.function.Consumer;

/**
 * @author zhangwenlong
 * @date 2019/8/25 16:02
 */
public class MethodReference {

    private static <T> void useConsumer(Consumer<T> consumer,T t){
        consumer.accept(t);
    }

    public static void main(String[] args) {
        //定義一個匿名類
        Consumer<String> stringConsumer = (s) -> System.out.println(s);
        useConsumer(stringConsumer,"Hello World");
        //lambda
        useConsumer((s) -> System.out.println(s),"ni hao");
        //Lambda的方法推導
        useConsumer(System.out::println,"da jia hao");
    }
}

執行結果:

Hello World
ni hao
da jia hao

參數推導其他例子:

package LambdaUse;

import java.net.Inet4Address;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * @author zhangwenlong
 * @date 2019/8/25 16:53
 */
public class paramterMethod {

    public static void main(String[] args) {
        //情況1:A method reference to a static method (for example, the method parseInt of Integer, written Integer::parseInt)
        //靜態方法
        //常用的使用
        Integer value = Integer.parseInt("123");
        System.out.println(value);
        //使用方法推導
        Function<String,Integer> stringIntegerFunction = Integer::parseInt;
        Integer apply = stringIntegerFunction.apply("123");
        System.out.println(apply);
        //情況2:A method reference to an instance method of an arbitrary type (for example, the method length of a String, written String::length)
        //對象的方法
        String ss = "helloWorld";
        System.out.println(ss.charAt(3));
        //推導方法
        BiFunction<String,Integer,Character> stringIntegerCharacterBiFunction = String::charAt;
        System.out.println(stringIntegerCharacterBiFunction.apply(ss,3));

        //情況3:構造函數方法推導
        //常用方式
        Apple apple = new Apple("蘋果",120);
        System.out.println(apple);
        //推導方式
        BiFunction<String,Integer,Apple> appleBiFunction = Apple::new;
        System.out.println(appleBiFunction.apply("蘋果",120));
    }
}

執行結果:

123
123
l
l
Apple{name='蘋果', weight=120}
Apple{name='蘋果', weight=120}

具體的詳細解釋可以參考:

方法推導詳解

#Stream(流以及一些常用的方法)
特點:並行處理
例子:

package StreamUse;

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

/**
 * @author zhangwenlong
 * @date 2019/8/25 17:20
 */
public class StreamTest {

    public static void main(String[] args) {
        List<Apple> appleList = Arrays.asList(
                new Apple("蘋果",110),
                new Apple("桃子",120),
                new Apple("荔枝",130),
                new Apple("香蕉",140),
                new Apple("火龍果",150),
                new Apple("芒果",160)
        );
        System.out.println(getNamesByCollection(appleList));
        System.out.println(getNamesByStream(appleList));
    }

    //collection實現查詢重量小於140的水果的名稱
    private static List<String> getNamesByCollection(List<Apple> appleList){
        List<Apple> apples = new ArrayList<>();

        //查詢重量小於140的水果
        for(Apple apple : appleList){
            if(apple.getWeight() < 140){
               apples.add(apple);
            }
        }
        //排序
        Collections.sort(apples,(a,b)->Integer.compare(a.getWeight(),b.getWeight()));

        List<String> appleNamesList = new ArrayList<>();
        for(Apple apple : apples){
            appleNamesList.add(apple.getName());
        }
        return  appleNamesList;
    }

    //stream實現查詢重量小於140的水果的名稱
    private static List<String> getNamesByStream(List<Apple> appleList){
        return  appleList.stream().filter(d ->d.getWeight() < 140)
                .sorted(Comparator.comparing(Apple::getWeight))
                .map(Apple::getName)
                .collect(Collectors.toList());
    }
}

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