小白近期簡單學習了一下Java8的幾個新特性,主要是Lambda表達式,函數式編程,Stream(流),現將學習的一些簡單的語句記錄下來,如有機會也可以幫助想簡單瞭解這類知識的人。
話不多說,直接上代碼(包含簡單講解)
public class LmdTest {
public static void main(String[] args) {
/*
* 一:Lambda,總的來說,只要是一個接口中只有一個抽象方法的,都可以實現lambda表達式
*/
// Lmd簡單調用,並返回參數
LmdString lmdStr = name -> "name:" + name;
System.out.println(lmdStr.rtnName("小白"));
//Lmd數字運算 +
LmdMath lmdMt1 = (numA, numB) -> numA + numB;
System.out.println("numA + numB:" + lmdMt1.math(3,3));
//Lmd數字運算 -
LmdMath lmdMt2 = (numA, numB) -> numA - numB;
System.out.println("numA - numB:" + lmdMt2.math(3,3));
//Lmd數字運算 *
LmdMath lmdMt3 = (numA, numB) -> numA * numB;
System.out.println("numA * numB:" + lmdMt3.math(3,3));
//Lmd數字運算 /
LmdMath lmdMt4 = (numA, numB) -> numA / numB;
System.out.println("numA / numB:" + lmdMt4.math(3,3));
/*
* 二:函數式編程
*/
// JDK 1.8 新增加的函數接口:java.util.function,它包含了很多類來支持Java的函數式編程
BiFunction<String,String,String> rtnHel = (a,b) -> a + b;
System.out.println(rtnHel.apply("Hi:","小白"));
Function<String,String> rtnHel1 = (a) -> a + "-1-";
Function<String,String> rtnHel2 = (a) -> a + "-2-";
// 函數式接口中,andThen與compose的區別
System.out.println("andThen:" + rtnHel1.andThen(rtnHel2).apply("xiao"));
System.out.println("compose:" + rtnHel1.compose(rtnHel2).apply("xiao"));
/*
* 三:Stream(流)
*/
Random random = new Random();
int org = 0, bound = 10;
// Stream 簡單用法
random.ints(org,bound).limit(10).forEach(System.out::println);
// Stream 複雜用法 + 解釋
List<Integer> list = random.ints(org,bound) // 生成大於org,小於bound的數字流
.limit(10) // 限制數量,不然會一直生成
.filter(num -> num <= 5) // 過濾,需要小於等於5
.map(num -> num + 10) // 過濾後的數字都加1
.boxed() // 轉換爲對象流
.collect(Collectors.toList()); // 轉爲List
System.out.println(list);
}
interface LmdString {
//Lambda表達式調用的方法
String rtnName(String name);
}
interface LmdMath {
//Lambda表達式調用的方法
int math(int numA, int numB);
}
}
運行結果分別爲:
name:小白
numA + numB:6
numA - numB:0
numA * numB:9
numA / numB:1
Hi:小白
andThen:xiao-1--2-
compose:xiao-2--1-
5
7
6
9
6
9
7
8
7
7
[15, 12, 12, 11, 15, 11, 10]
Process finished with exit code 0