Java8: 感受 lambda 之美!

作者:9 龍

來源:juejin.cn/post/6844903849753329678

一、引言

java8 最大的特性就是引入 Lambda 表達式,即函數式編程,可以將行爲進行傳遞。總結就是:使用不可變值與函數,函數對不可變值進行處理,映射成另一個值。

二、java 重要的函數式接口

1、什麼是函數式接口

函數接口是隻有一個抽象方法的接口,用作 Lambda 表達式的類型。使用 @FunctionalInterface 註解修飾的類,編譯器會檢測該類是否只有一個抽象方法或接口,否則,會報錯。可以有多個默認方法,靜態方法。

1.1 java8 自帶的常用函數式接口。

Fpireh

public class Test {
    public static void main(String[] args) {
        Predicate<Integer> predicate = x -> x > 185;
        Student student = new Student("9龍", 23, 175);
        System.out.println(
            "9龍的身高高於185嗎?:" + predicate.test(student.getStature()));

        Consumer<String> consumer = System.out::println;
        consumer.accept("命運由我不由天");

        Function<Student, String> function = Student::getName;
        String name = function.apply(student);
        System.out.println(name);

        Supplier<Integer> supplier = 
            () -> Integer.valueOf(BigDecimal.TEN.toString());
        System.out.println(supplier.get());

        UnaryOperator<Boolean> unaryOperator = uglily -> !uglily;
        Boolean apply2 = unaryOperator.apply(true);
        System.out.println(apply2);

        BinaryOperator<Integer> operator = (x, y) -> x * y;
        Integer integer = operator.apply(2, 3);
        System.out.println(integer);

        test(() -> "我是一個演示的函數式接口");
    }

    /**
     * 演示自定義函數式接口使用
     *
     * @param worker
     */
    public static void test(Worker worker) {
        String work = worker.work();
        System.out.println(work);
    }

    public interface Worker {
        String work();
    }
}
//9龍的身高高於185嗎?:false
//命運由我不由天
//9龍
//10
//false
//6
//我是一個演示的函數式接口

以上演示了 lambda 接口的使用及自定義一個函數式接口並使用。下面,我們看看 java8 將函數式接口封裝到流中如何高效的幫助我們處理集合。

注意:Student::getName 例子中這種編寫 lambda 表達式的方式稱爲方法引用。格式爲 ClassNmae::methodName。是不是很神奇,java8 就是這麼迷人。

示例:本篇所有示例都基於以下三個類。OutstandingClass:班級;Student:學生;SpecialityEnum:特長。

1.2 惰性求值與及早求值

惰性求值:只描述 Stream,操作的結果也是 Stream,這樣的操作稱爲惰性求值。惰性求值可以像建造者模式一樣鏈式使用,最後再使用及早求值得到最終結果。

及早求值:得到最終的結果而不是 Stream,這樣的操作稱爲及早求值。

2、常用的流

2.1 collect(Collectors.toList())

將流轉換爲 list。還有 toSet(),toMap() 等。及早求值

public class TestCase {
    public static void main(String[] args) {
        List<Student> studentList = Stream.of(new Student("路飛", 22, 175),
                new Student("紅髮", 40, 180),
                new Student("白鬍子", 50, 185)).collect(Collectors.toList());
        System.out.println(studentList);
    }
}
//輸出結果
//[Student{name='路飛', age=22, stature=175, specialities=null}, 
//Student{name='紅髮', age=40, stature=180, specialities=null}, 
//Student{name='白鬍子', age=50, stature=185, specialities=null}]

2.2 filter

顧名思義,起過濾篩選的作用。內部就是 Predicate 接口。惰性求值。

比如我們篩選出出身高小於 180 的同學。

public class TestCase {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(3);
        students.add(new Student("路飛", 22, 175));
        students.add(new Student("紅髮", 40, 180));
        students.add(new Student("白鬍子", 50, 185));

        List<Student> list = students.stream()
            .filter(stu -> stu.getStature() < 180)
            .collect(Collectors.toList());
        System.out.println(list);
    }
}
//輸出結果
//[Student{name='路飛', age=22, stature=175, specialities=null}]

2.3 map

轉換功能,內部就是 Function 接口。惰性求值

public class TestCase {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(3);
        students.add(new Student("路飛", 22, 175));
        students.add(new Student("紅髮", 40, 180));
        students.add(new Student("白鬍子", 50, 185));

        List<String> names = students.stream().map(student -> student.getName())
                .collect(Collectors.toList());
        System.out.println(names);
    }
}
//輸出結果
//[路飛, 紅髮, 白鬍子]

例子中將 student 對象轉換爲 String 對象,獲取 student 的名字。

2.4 flatMap

將多個 Stream 合併爲一個 Stream。惰性求值

public class TestCase {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(3);
        students.add(new Student("路飛", 22, 175));
        students.add(new Student("紅髮", 40, 180));
        students.add(new Student("白鬍子", 50, 185));

        List<Student> studentList = Stream.of(students,
                asList(new Student("艾斯", 25, 183),
                        new Student("雷利", 48, 176)))
                .flatMap(students1 -> students1.stream()).collect(Collectors.toList());
        System.out.println(studentList);
    }
}
//輸出結果
//[Student{name='路飛', age=22, stature=175, specialities=null}, 
//Student{name='紅髮', age=40, stature=180, specialities=null}, 
//Student{name='白鬍子', age=50, stature=185, specialities=null}, 
//Student{name='艾斯', age=25, stature=183, specialities=null},
//Student{name='雷利', age=48, stature=176, specialities=null}]

調用 Stream.of 的靜態方法將兩個 list 轉換爲 Stream,再通過 flatMap 將兩個流合併爲一個。

2.5 max 和 min

我們經常會在集合中求最大或最小值,使用流就很方便。及早求值。

public class TestCase {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(3);
        students.add(new Student("路飛", 22, 175));
        students.add(new Student("紅髮", 40, 180));
        students.add(new Student("白鬍子", 50, 185));

        Optional<Student> max = students.stream()
            .max(Comparator.comparing(stu -> stu.getAge()));
        Optional<Student> min = students.stream()
            .min(Comparator.comparing(stu -> stu.getAge()));
        //判斷是否有值
        if (max.isPresent()) {
            System.out.println(max.get());
        }
        if (min.isPresent()) {
            System.out.println(min.get());
        }
    }
}
//輸出結果
//Student{name='白鬍子', age=50, stature=185, specialities=null}
//Student{name='路飛', age=22, stature=175, specialities=null}

max、min 接收一個 Comparator(例子中使用 java8 自帶的靜態函數,只需要傳進需要比較值即可。)並且返回一個 Optional 對象,該對象是 java8 新增的類,專門爲了防止 null 引發的空指針異常。可以使用 max.isPresent() 判斷是否有值;可以使用 max.orElse(new Student()),當值爲 null 時就使用給定值;也可以使用 max.orElseGet(() -> new Student()); 這需要傳入一個 Supplier 的 lambda 表達式。

2.6 count

統計功能,一般都是結合 filter 使用,因爲先篩選出我們需要的再統計即可。及早求值

public class TestCase {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(3);
        students.add(new Student("路飛", 22, 175));
        students.add(new Student("紅髮", 40, 180));
        students.add(new Student("白鬍子", 50, 185));

        long count = students.stream().filter(s1 -> s1.getAge() < 45).count();
        System.out.println("年齡小於45歲的人數是:" + count);
    }
}
//輸出結果
//年齡小於45歲的人數是2

2.7 reduce

reduce 操作可以實現從一組值中生成一個值。在上述例子中用到的 count 、 min 和 max 方 法,因爲常用而被納入標準庫中。事實上,這些方法都是 reduce 操作。及早求值。

public class TestCase {
    public static void main(String[] args) {
        Integer reduce = Stream.of(1, 2, 3, 4).reduce(0, (acc, x) -> acc+ x);
        System.out.println(reduce);
    }
}
//輸出結果
//10

我們看得 reduce 接收了一個初始值爲 0 的累加器,依次取出值與累加器相加,最後累加器的值就是最終的結果。

三、高級集合類及收集器

3.1 轉換成值

收集器,一種通用的、從流生成複雜值的結構。只要將它傳給 collect 方法,所有 的流就都可以使用它了。標準類庫已經提供了一些有用的收集器,以下示例代碼中的收集器都是從 java.util.stream.Collectors 類中靜態導入的。

public class CollectorsTest {
    public static void main(String[] args) {
        List<Student> students1 = new ArrayList<>(3);
        students1.add(new Student("路飛", 23, 175));
        students1.add(new Student("紅髮", 40, 180));
        students1.add(new Student("白鬍子", 50, 185));

        OutstandingClass ostClass1 = new OutstandingClass("一班", students1);
        //複製students1,並移除一個學生
        List<Student> students2 = new ArrayList<>(students1);
        students2.remove(1);
        OutstandingClass ostClass2 = new OutstandingClass("二班", students2);
        //將ostClass1、ostClass2轉換爲Stream
        Stream<OutstandingClass> classStream = Stream.of(ostClass1, ostClass2);
        OutstandingClass outstandingClass = biggestGroup(classStream);
        System.out.println("人數最多的班級是:" + outstandingClass.getName());

        System.out.println("一班平均年齡是:" + averageNumberOfStudent(students1));
    }

    /**
     * 獲取人數最多的班級
     */
    private static OutstandingClass biggestGroup(Stream<OutstandingClass> outstandingClasses) {
        return outstandingClasses.collect(
                maxBy(comparing(ostClass -> ostClass.getStudents().size())))
                .orElseGet(OutstandingClass::new);
    }

    /**
     * 計算平均年齡
     */
    private static double averageNumberOfStudent(List<Student> students) {
        return students.stream().collect(averagingInt(Student::getAge));
    }
}
//輸出結果
//人數最多的班級是:一班
//一班平均年齡是37.666666666666664

maxBy 或者 minBy 就是求最大值與最小值。

3.2 轉換成塊

常用的流操作是將其分解成兩個集合,Collectors.partitioningBy 幫我們實現了,接收一個 Predicate 函數式接口。

將示例學生分爲會唱歌與不會唱歌的兩個集合。

public class PartitioningByTest {
    public static void main(String[] args) {
        //省略List<student> students的初始化
        Map<Boolean, List<Student>> listMap = students.stream().collect(
            Collectors.partitioningBy(student -> student.getSpecialities().
                                      contains(SpecialityEnum.SING)));
    }
}

3.3 數據分組

數據分組是一種更自然的分割數據操作,與將數據分成 ture 和 false 兩部分不同,可以使****用任意值對數據分組。Collectors.groupingBy 接收一個 Function 做轉換。

如圖,我們使用 groupingBy 將根據進行分組爲圓形一組,三角形一組,正方形一組。

例子:根據學生第一個特長進行分組

public class GroupingByTest {
    public static void main(String[] args) {
        //省略List<student> students的初始化
         Map<SpecialityEnum, List<Student>> listMap = 
             students.stream().collect(
             Collectors.groupingBy(student -> student.getSpecialities().get(0)));
    }
}

Collectors.groupingBy 與 SQL 中的 group by 操作是一樣的。

3.4 字符串拼接

如果將所有學生的名字拼接起來,怎麼做呢?通常只能創建一個 StringBuilder,循環拼接。使用 Stream,使用 Collectors.joining() 簡單容易。

public class JoiningTest {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(3);
        students.add(new Student("路飛", 22, 175));
        students.add(new Student("紅髮", 40, 180));
        students.add(new Student("白鬍子", 50, 185));

         String names = students.stream()
             .map(Student::getName).collect(Collectors.joining(",","[","]"));
        System.out.println(names);
    }
}
//輸出結果
//[路飛,紅髮,白鬍子]

joining 接收三個參數,第一個是分界符,第二個是前綴符,第三個是結束符。也可以不傳入參數 Collectors.joining(),這樣就是直接拼接。

四、總結

本篇主要從實際使用講述了常用的方法及流,使用 java8 可以很清晰表達你要做什麼,代碼也很簡潔。本篇例子主要是爲了講解較爲簡單,大家可以去使用 java8 重構自己現有的代碼,自行領會 lambda 的奧妙。本文說的 Stream 要組合使用纔會發揮更大的功能,鏈式調用很迷人,根據自己的業務去做吧。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/_eydum2I0XzoBnJcUWHV5Q