您好,登錄后才能下訂單哦!
[TOC]
最近在看一些開源項目的源碼,函數(shù)式編程風(fēng)格的代碼無處不在,所以得要好好學(xué)一下了。
無參數(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;
每個函數(shù)接口列舉一些例子來說明。
判斷一個數(shù)是否為偶數(shù)。
Predicate<Integer> isEven = x -> x % 2 == 0;
System.out.println(isEven.test(3)); // false
打印字符串。
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);
將數(shù)字加1后轉(zhuǎn)換為字符串。
Function<Integer, String> addThenStr = num -> (++num).toString();
String res = addThenStr.apply(3);
System.out.println(res); // 4
創(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
實現(xiàn)一元操作符求絕對值。
UnaryOperator<Integer> abs = num -> -num;
System.out.println(abs.apply(-3)); // 3
實現(xiàn)二元操作符相加。
BinaryOperator<Integer> multiply = (x, y) -> x * y;
System.out.println(multiply.apply(3, 4)); // 12
免責(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)容。