溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2020-06-14 20:34:27 來源:網(wǎng)絡(luò) 閱讀:1165 作者:xpleaf 欄目:編程語言

[TOC]


1 前言

最近在看一些開源項目的源碼,函數(shù)式編程風(fēng)格的代碼無處不在,所以得要好好學(xué)一下了。

2 Lambda表達式類型

無參數(shù):

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

一個參數(shù):

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

多行語句:

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

兩個參數(shù):

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

顯式類型:

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

3 常用函數(shù)接口

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

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

3.1 Predicate<T>

判斷一個數(shù)是否為偶數(shù)。

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>

將數(shù)字加1后轉(zhuǎn)換為字符串。

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

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

3.4 Supplier<T>

創(chuàng)建一個獲取常用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>

實現(xiàn)一元操作符求絕對值。

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

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

3.6 BinaryOperator<T>

實現(xiàn)二元操作符相加。

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

System.out.println(multiply.apply(3, 4));   // 12
向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI