1. 程式人生 > >Java8函數式編程(一):Lambda表達式類型與常用函數接口

Java8函數式編程(一):Lambda表達式類型與常用函數接口

led ebe 前言 eve 分享 3.1 integer water 代碼

[TOC]


1 前言

最近在看一些開源項目的源碼,函數式編程風格的代碼無處不在,所以得要好好學一下了。

2 Lambda表達式類型

無參數:

Runnable noArguments = () -> System.out.println("Hello World!");
noArguments.run();

一個參數:

UnaryOperator<Boolean> oneArgument = x -> !x;
System.out.println(oneArgument.apply(true));

多行語句:

Runnable multiStatement = () -> {
    System.out.print("Hello");
    System.out.println(" World!");
};

兩個參數:

BinaryOperator<Integer> add = (x, y) -> x + y;
add.apply(1, 2);

顯式類型:

BinaryOperator<Integer> addExplicit = (Integer x, Integer y) -> x + y;

3 常用函數接口

技術分享圖片

每個函數接口列舉一些例子來說明。

3.1 Predicate<T>

判斷一個數是否為偶數。

Predicate<Integer> isEven = x -> x % 2 == 0;

System.out.println(isEven.test(3)); // false

3.2 Consumer<T>

打印字符串。

Consumer<String> printStr = s -> System.out.println("start#" + s + "#end");

printStr.accept("hello");   // start#hello#end
List<String> list = new ArrayList<String>(){{
    add("hello");
    add("world");
}};
list.forEach(printStr);

3.3 Function<T,R>

將數字加1後轉換為字符串。

Function<Integer, String> addThenStr = num -> (++num).toString();

String res = addThenStr.apply(3);
System.out.println(res);    // 4

3.4 Supplier<T>

創建一個獲取常用SimpleDateFormat的Lambda表達式。

Supplier<SimpleDateFormat> normalDateFormat = () -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

SimpleDateFormat sdf = normalDateFormat.get();
Date date = sdf.parse("2019-03-29 23:24:05");
System.out.println(date);   // Fri Mar 29 23:24:05 CST 2019

3.5 UnaryOperator<T>

實現一元操作符求絕對值。

UnaryOperator<Integer> abs = num -> -num;

System.out.println(abs.apply(-3));  // 3

3.6 BinaryOperator<T>

實現二元操作符相加。

BinaryOperator<Integer> multiply = (x, y) -> x * y;

System.out.println(multiply.apply(3, 4));   // 12

Java8函數式編程(一):Lambda表達式類型與常用函數接口