溫馨提示×

溫馨提示×

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

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

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

發布時間:2020-06-14 20:34:27 來源:網絡 閱讀:1187 作者:xpleaf 欄目:編程語言

[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 常用函數接口

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

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

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
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女