一、lambda運算式
介紹
1). 使代碼更加簡潔;
2)可以配合很多新特性使用,編程更加優雅
例如:Runable
以前的寫法
public class LambdaTest1 {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
System.out.println("老方式實作一個執行緒");
}
};
new Thread(runnable).start();
}
}
現在的寫法
new Thread(()-> System.out.println("lamda運算式啟動")).start();
解釋畫圖對比:
//lambda ():引數 ->:引數指向代碼題的固定寫法
//lambda: 當前介面有且僅有一個抽象方法
Runnable runnable = ()-> System.out.println(Thread.currentThread().getName()+"啟動了...");
new Thread(runnable).start();
原理就是,編譯器在當前類中生成一個內部類,在生成一個靜態方法,靜態方法就是lambda運算式中的代碼
javap -p xxx.class
javap -c -p xxxx.class
二、函式式介面
Lambda的語法非常簡潔,完全沒有面向物件復雜的束縛,但是使用時需要特別注意:
1). 使用Lambda必須具有介面,且要求介面中有且僅有一個抽象方法,
2). 有且僅有一個抽象方法的介面,稱為“函式式介面”,
2.1 格式
只要確保介面中有且僅有一個抽象方法即可:
修飾符 interface 介面名稱 {
public abstract 回傳值型別 方法名稱(可選引數資訊);
// 其他非抽象方法內容
}
由于介面當中抽象方法的 public abstract 是可以省略的,所以定義一個函式式介面很簡單:
public interface MyFunctionalInterface {
void myMethod();
}
2.2 @FunctionalInterface注解
與 @Override 注解的作用類似,Java 8中專門為函式式介面引入了一個新的注解: @FunctionalInterface ,該注解可用于一個介面的定義上
@FunctionalInterface
public interface MyFunctionalInterface {
void myMethod();
}
一旦使用該注解來定義介面,編譯器將會強制檢查該介面是否確實有且僅有一個抽象方法,否則將會報錯,需要注意的是,即使不使用該注解,只要滿足函式式介面的定義,這仍然是一個函式式介面,使用起來都一樣,
2.3 練習
2.3.1 無參無回傳
給定一個汽車Car 介面,內含唯一的抽象方法 run,且無引數、無回傳值,如下:
public interface Car {
void run();
}
在下面的代碼中,請使用Lambda的標準格式呼叫 run方法,列印輸出“喝車不開酒!”字樣:
public class CarDemo{
public static void main(String[] args) {
//todo 寫上lambda運算式
}
private static void go(Car car){
car.run();
}
}
答案:
go(()-> System.out.println("喝車不開酒"));
備注:小括號代表 Car介面 run抽象方法的引數為空,大括號代表 run的方法體,
2.3.2 Lambda的引數和回傳值
下面舉例演示 java.util.Comparator 介面的使用場景代碼,其中的抽象方法定義為:
public abstract int compare(T o1, T o2);
當需要對一個物件陣列進行排序時, Arrays.sort 方法需要一個 Comparator 介面實體來指定排序的規則,假設有一個 Person 類,含有 String name 和 int age 兩個成員變數:
public class Person {
private String name;
private int age;
// 省略構造器、toString方法與Getter Setter
}
傳統寫法
如果使用傳統的代碼對 Person[] 陣列進行排序,寫法如下:
public class PersonTest {
public static void main(String[] args) {
// 本來年齡亂序的物件陣列
Person[] array = {
new Person(19,"橋本有菜" ),
new Person(28,"沖田杏梨"),
new Person(26,"明榷訓綺羅") };
// 匿名內部類
Comparator<Person> comp = new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
};
Arrays.sort(array, comp); // 第二個引數為排序規則,即Comparator介面實體
for (Person person : array) {
System.out.println(person);
}
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person{
private int age;
private String name;
}
這種做法在面向物件的思想中,似乎也是“理所當然”的,其中 Comparator 介面的實體(使用了匿名內部類)代表了“按照年齡從小到大”的排序規則,
改成lambda運算式:
//lambda運算式 實作排序物件
Arrays.sort(array, (Person a ,Person b)->{
return a.getAge()-b.getAge();
});
例:
interface Compute {
int compute(int a, int b);
}
public class ComputeDemo{
public static void main(String[] args) {
//todo 使用lambda運算式呼叫subtract方法
}
private static int subtract(int a,int b,Compute compute){
return compute.compute(a,b);
}
}
答案:
//todo 使用lambda運算式呼叫subtract方法
int subtract = subtract(1, 2, (int a, int b) -> {
return a - b;
});
System.out.println(subtract);
2.3.3 Lambda省略格式
可推導即可省略
省略規則
在Lambda標準格式的基礎上,使用省略寫法的規則為:
- 小括號內引數的型別可以省略;
- 如果小括號內有且僅有一個參,則小括號可以省略;
- 如果大括號內有且僅有一個陳述句,則無論是否有回傳值,都可以省略大括號、return關鍵字及陳述句分號,
那么上面的寫法可以簡寫為:
Compute compute = (a,b) -> a - b;
//todo 使用lambda運算式呼叫subtract方法
int subtract = subtract(1, 2,compute);
2.4 Lambda的延遲執行
有些場景的代碼執行后,結果不一定會被使用,從而造成性能浪費,而Lambda運算式是延遲執行的,這正好可以作為解決方案,提升性能,
性能浪費的日志案例
注:日志可以幫助我們快速的定位問題,記錄程式運行程序中的情況,以便專案的監控和優化,
一種典型的場景就是對引數進行有條件使用,例如對日志訊息進行拼接后,在滿足條件的情況下進行列印輸出:
public class MyLogger {
public static void printLog(String level,String msg){
if("error".equals(level)){
System.out.println(msg);
}
}
public static void main(String[] args) {
String classMessage = "出現例外的類為Student";
String errorMessage = "出現了空指標例外";
printLog("error",classMessage+errorMessage);
//沒有滿足error條件 ,那么這里的字串拼接是沒有意義的
printLog("debug",classMessage+errorMessage);
}
}
備注:SLF4J是應用非常廣泛的日志框架,它在記錄日志時為了解決這種性能浪費的問題,并不推薦首先進行字串的拼接,而是將字串的若干部分作為可變引數傳入方法中,僅在日志級別滿足要求的情況下才會進行字串拼接,例如: LOGGER.debug(“變數{}的取值為{},”, “os”, “macOS”) ,其中的大括號 {} 為占位符,如果滿足日志級別要求,則會將“os”和“macOS”兩個字串依次拼接到大括號的位置;否則不會進行字串拼接,lambda也可以實作
lambda實作
public class MyLogger {
public static void printLog(String level,Message message){
if("error".equals(level)){
System.out.println(message.getMessage());
}
}
public static void main(String[] args) {
String classMessage = "出現例外的類為Student";
String errorMessage = "出現了空指標例外";
printLog("error",()->{
System.out.println("滿足條件執行");
return classMessage+errorMessage;
});
//沒有滿足error條件 ,那么這里的字串拼接是沒有意義的
printLog("debug",()->{
System.out.println("不滿足條件不執行");
return classMessage+errorMessage;
});
}
}
@FunctionalInterface
interface Message{
String getMessage();
}
2.5 常用的函式式介面
jdk為了我們在使用lambda的時候更加簡便,也為我們提供了大量的函式式介面,供我們使用
2.5.1 Supplier介面
ava.util.function.Supplier 介面僅包含一個無參的方法: T get() ,用來獲取一個泛型引數指定型別的對
象資料,由于這是一個函式式介面,這也就意味著對應的Lambda運算式需要“對外提供”一個符合泛型型別的物件資料,
public class SupplierDemo {
public static void main(String[] args) {
Supplier supplier =()->"hello"+"world";
//也就是說以后需要回傳值,但是沒有引數的lambda運算式的時候可以使用該介面
System.out.println(supplier.get());
}
}
2.5.2 Consumer介面
java.util.function.Consumer 介面則正好與Supplier介面相反,它不是生產一個資料,而是消費一個資料,其資料型別由泛型決定,
public class ConsumerDemo {
public static void main(String[] args) {
//消費一個a字串 沒有回傳值
Consumer<String> consumer =a->System.out.println(a);
consumer.accept("hello");
}
}
addThen方法,連續消費
public class ConsumerDemo {
public static void main(String[] args) {
Consumer<String> consumer1 = a-> System.out.println(a.toUpperCase());
Consumer<String> consumer2 = a-> System.out.println(a.substring(1));
//先完成第一個消費 再消費第二個
consumer1.andThen(consumer2).accept("!hello word");
}
}
2.5.3 Predicate介面
有時候我們需要對某種型別的資料進行判斷,從而得到一個boolean值結果,這時可以使用java.util.function.Predicate 介面,
public class PredicateTest {
public static void main(String[] args) {
// boolean test(T t);
//傳入一個Integer型別的引數 判斷是否大于1
Predicate<Integer> predicate = a ->a>1;
System.out.println(predicate.test(1));
}
}
and方法,表示兩個條件要同時滿足
public class PredicateTest {
public static void main(String[] args) {
// boolean test(T t);
//傳入一個Integer型別的引數 判斷是否大于1
Predicate<Integer> predicate1 = a ->a>1;
Predicate<Integer> predicate2 = a ->a<10;
//需要同時滿足 a>1 && a<10
System.out.println(predicate1.and(predicate2).test(10));
}
}
or類似
negate:取反,比如第一個例子加上就是true了
public class PredicateTest {
public static void main(String[] args) {
// boolean test(T t);
//傳入一個Integer型別的引數 判斷是否大于1
Predicate<Integer> predicate = a ->a>1;
System.out.println(predicate.negate().test(1));
}
}
2.5.4 Function介面
java.util.function.Function<T,R> 介面用來根據一個型別的資料得到另一個型別的資料,前者稱為前置條件,后者稱為后置條件,
apply方法
public class FunctionTest {
public static void main(String[] args) {
//前面的泛型是傳入的型別 后面的泛型是回傳值的型別
Function<String,Integer> function = a->Integer.valueOf(a);
Integer apply = function.apply("100");
System.out.println(apply);
}
}
默認方法:andThen 組裝兩個function介面
public class FunctionTest {
public static void main(String[] args) {
//前面的泛型是傳入的型別 后面的泛型是回傳值的型別
Function<String,Integer> function1 = a->Integer.valueOf(a);
Function<Integer,Integer> function2 = a->a+50;
//先轉換成數字再加50
System.out.println(function1.andThen(function2).apply("100"));
}
}
其它函式介面,用的比較少,就不做贅述了,
三、Stream
說到Stream便容易想到I/O Stream,而實際上,誰規定“流”就一定是“IO流”呢?在Java 8中,得益于Lambda所帶來的函式式編程,引入了一個全新的Stream概念,用于解決已有集合類別庫既有的弊端,
首先流操作可以使得代碼看起來更加的簡潔,美觀等,不說那么多廢話,直接開始demo
3.1 獲取流
ava.util.stream.Stream 是Java 8新加入的最常用的流介面,(這并不是一個函式式介面,)
獲取一個流非常簡單,有以下幾種常用的方式:
所有的 Collection 集合都可以通過 stream 默認方法獲取流;
Stream 介面的靜態方法 of 可以獲取陣列對應的流,
根據Collection獲取流
首先, java.util.Collection 介面中加入了default方法 stream 用來獲取流,所以其所有實作類均可獲取流,
List<String> list = new ArrayList<>();
Stream<String> stream1 = list.stream();
Set<String> set = new HashSet<>();
Stream<String> stream2 = set.stream();
Vector<String> vector = new Vector<>();
Stream<String> stream3 = vector.stream();
//MAP集合
Map<String, String> map = new HashMap<>();
Stream<String> keyStream = map.keySet().stream();
Stream<String> valueStream = map.values().stream();
Stream<Map.Entry<String, String>> entryStream = map.entrySet().stream();
//陣列 of 方法的引數其實是一個可變引數
String[] array = { "張無忌", "張翠山", "張三豐", "張一元" };
Stream<String> stream = Stream.of(array);
//無限流
//通過生成器產生5個10以內的亂數,如果不使用limit就會無限生成10以內亂數
Stream.generate(() -> Math.random() * 10).limit(5).forEach(System.out::println);
//通過迭代的方式(一元運算)生成5個數
Stream.iterate(0,x->x+2).limit(5).forEach(System.out::println);
3.2 常用方法
流模型的操作很豐富,這里介紹一些常用的API,這些方法可以被分成兩種:
延遲方法:回傳值型別仍然是 Stream 介面自身型別的方法,因此支持鏈式呼叫,(除了終結方法外,其余方法均為延遲方法,)
終結方法:回傳值型別不再是 Stream 介面自身型別的方法,因此不再支持類似 StringBuilder 那樣的鏈式呼叫,本小節中,終結方法包括 count 和 forEach 方法,
3.2.1 逐一處理:forEach
void forEach(Consumer<T> action);
該方法接收一個 Consumer 介面函式,會將每一個流元素交給該函式進行處理,
Stream<String> stream = Stream.of("張三", "李四", "王五");
stream.forEach(name‐> System.out.println(name));
3.2.2 過濾:filter
可以通過 filter 方法將一個流轉換成另一個子集流,方法簽名:
Stream<T> filter(Predicate<? super T> predicate);
該介面接收一個 Predicate 函式式介面引數(可以是一個Lambda或方法參考)作為篩選條件,
基本使用
Stream<String> original = Stream.of("張三", "張三豐", "李四");
//過濾姓名以張開頭的名字
Stream<String> stream = original.filter(s -> s.startsWith("張"));
stream.forEach(a-> System.out.println(a));
// 寫成一行
original.filter(s -> s.startsWith("張")).forEach(a-> System.out.println(a));
3.2.3 映射:map
如果需要將流中的元素映射到另一個流中,可以使用 map 方法,方法簽名:
<R> Stream<R> map(Function<? super T,? extends R> mapper);
該介面需要一個 Function 函式式介面引數,可以將當前流中的T型別資料轉換為另一種R型別的流,
基本使用
//將一個string型別的流 ----T 轉換為一個Integer型別的流-----R
Stream<String> original = Stream.of("10", "12", "18");
Stream<Integer> result = original.map(str->Integer.parseInt(str));
result.forEach(a-> System.out.println(a));
3.2.4 統計個數:count
long count();
Stream<String> original = Stream.of("張三", "張三豐", "李四");
Stream<String> result = original.filter(s ‐> s.startsWith("張"));
System.out.println(result.count()); // 2
3.2.5 取用前幾個:limit
limit 方法可以對流進行截取,只取用前n個,方法簽名:
Stream<T> limit(long maxSize);
引數是一個long型,如果集合當前長度大于引數則進行截取;否則不進行操作,
基本使用
Stream<String> original = Stream.of("張三", "張三豐", "李四");
Stream<String> result = original.limit(2);
System.out.println(result.count()); // 2
3.2.6 跳過前幾個:skip
如果希望跳過前幾個元素,可以使用 skip 方法獲取一個截取之后的新流:
Stream<T> skip(long n);
如果流的當前長度大于n,則跳過前n個;否則將會得到一個長度為0的空流,
基本使用:
Stream<String> original = Stream.of("張三", "張三豐", "李四");
Stream<String> result = original.skip(2);
System.out.println(result.count()); // 1
3.2.7 組合:concat
如果有兩個流,希望合并成為一個流,那么可以使用 Stream 介面的靜態方法 concat :
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)
基本使用:
Stream<String> streamA = Stream.of("張三");
Stream<String> streamB = Stream.of("張三豐");
Stream<String> result = Stream.concat(streamA, streamB);
result.forEach(a-> System.out.println(a));
3.2.8 distinct----篩選 sorted----排序
distinct----篩選,通過流所所生成元素的hashCode()和equals()去除重復元素
List<Integer> list = Arrays.asList(4,2,2,1,3,3,2,4);
//去重
Stream<Integer> stream3 = list.stream().distinct();
stream3.forEach(System.out::println);
System.out.println("----------------排序后---------------");
//排序后
Stream<Integer> stream4 = list.stream().distinct().sorted();
stream4.forEach(System.out::println);
3.2.9 flatMap(扁平化處理)、map
List<String> stringList = Arrays.asList("niu", "pi");
List<String[]> collect = stringList.stream().map(s -> s.split("")).collect(Collectors.toList());
List<String> collect1 = stringList.stream().flatMap(s -> Arrays.stream(s.split(""))).collect(Collectors.toList());
3.2.10 allMatch----檢查是否匹配所有元素
List<Integer> numbers = Arrays.asList(3,7,8, 10, 2);
//必須里面所有元素大于3才回傳true
boolean b = numbers.stream().allMatch(a -> a > 3);
System.out.println(b);
3.2.11 anyMatch----檢查是否有匹配至少一個元素
List<Integer> numbers = Arrays.asList(3,7,8, 10, 2);
//必須里面只要有元素大于3回傳true
boolean b = numbers.stream().anyMatch(a -> a > 3);
System.out.println(b);
3.2.12 noneMatch----檢查是否沒有匹配的元素
List<Integer> numbers = Arrays.asList(3,7,8, 10, 2);
//沒有元素大于11就回傳true
boolean b = numbers.stream().noneMatch(a -> a > 11);
System.out.println(b);
3.2.13 findFirst----回傳第一個元素
List<Integer> numbers = Arrays.asList(3,7,8, 10, 2);
Optional<Integer> first = numbers.stream().findFirst();
if(first.isPresent()){
System.out.println(first.get());
}
3.2.14 findAny----回傳當前流中的任意一元素
3.2.15 max----回傳流中最大值
3.2.16 min----回傳流中的最小值
3.2.17 reduce(T identity,BinaryOperator)
可以將流中元素反復結合起來得到一個值,回傳T
List<Integer> numbers = Arrays.asList(3,7,8, 10, 2);
Integer reduce = numbers.stream().reduce(0, (x, y) -> x + y);
System.out.println(reduce);
3.2.18 collect
將流轉換為其他形式,接收一個Collector介面的實作,用于給Stream中元素做匯總的方法
@Data
@AllArgsConstructor
@NoArgsConstructor
class Student{
private String name;
private int age;
}
List<Student> students = Arrays.asList(new Student("張三", 100), new Student("李四", 200), new Student("王五", 300));
//集合轉map key不唯一會報錯
Map<String, Student> collect = students.stream().collect(Collectors.toMap(s -> s.getName(), s -> s));
System.out.println(collect);
//map的value轉集合
List<Student> collect1 = collect.values().stream().collect(Collectors.toList());
System.out.println(collect1);
//map轉set
Set<Student> collect2 = collect.values().stream().collect(Collectors.toSet());
System.out.println(collect2);
//map轉其它自定義集合 treeSet linkedList等都一樣
CopyOnWriteArrayList<Student> collect3 = collect.values().stream().collect(Collectors.toCollection(CopyOnWriteArrayList::new));
CopyOnWriteArrayList<Student> collect4 = collect.values().stream().collect(Collectors.toCollection(()->new CopyOnWriteArrayList<>()));
//將map value中的名字取出來并以-鏈接
String collect5 = collect.values().stream().map(s -> s.getName()).collect(Collectors.joining("-"));
System.out.println(collect5);
String collect6 = collect.values().stream().map(s -> s.getName()).collect(Collectors.joining("-", "aaa", "zzzz"));
System.out.println(collect6);
// 根據指定條件取最大值: 取年紀最大的人
Optional<User> optional = listUser.stream().collect(Collectors.maxBy(Comparator.comparing((user) -> {
return user.getAge();
})));
if (optional.isPresent()) { // 判斷是否有值
User user = optional.get();
System.out.println("最大年紀的人是:" + user.getName()); // 輸出==》 最大年紀的人是:杜甫
}
Double averageAge = listUser.stream().collect(Collectors.averagingInt(User::getAge));
System.out.println("平均年齡是:" + averageAge); // 輸出--》 平均年齡是:26.0
Long count = listUser.stream().filter(user -> user.getGender()).collect(Collectors.counting());
System.out.println("男性個數:" + count); // 輸出--》 男性個數:2 跳過
Function<User, String> classifier = (user) -> {
return user.getName();
};
Map<String, List<User>> groupby = listUser.stream().collect(Collectors.groupingBy(classifier));
Collectors.toMap:獲得一個map
Collectors.toList:獲得一個list集合
Collectors.toSet():獲得一個set集合
注:collect里面操作很多,一下是記不完的,先把這些常用的記住以后遇到什么查API就可以了
3.2.19 并行流
List<Student> students = Arrays.asList(new Student("張三", 100), new Student("李四", 200), new Student("王五", 300));
//多執行緒操作
List<Student> collect = students.parallelStream().map(s -> {
System.out.println(Thread.currentThread().getName());
return s;
}).collect(Collectors.toList());
System.out.println(collect);
//串行流 轉并行流
students.stream().parallel().map(s->{
System.out.println(Thread.currentThread().getName());
return s;
}).collect(Collectors.toList()).forEach(System.out::println);
//并行流是使用的jdk1.7的fork/join框架
// fork的意思是將任務拆分為小的,join的意思是將小結果組裝為大結果 典型演算法中的分治演算法/竊取演算法
//自定義執行緒池個數
System.out.println("自定義執行緒池個數");
ForkJoinPool forkJoinPool = new ForkJoinPool(3);
forkJoinPool.submit(()->students.parallelStream().map(s->{
System.out.println(Thread.currentThread().getName());
return s;
}).collect(Collectors.toList()).forEach(System.out::println)).get();
3.3 中間操作、終止操作
基本上,上面的方法中回傳是stream的基本都是中間操作
回傳其它的是終止操作
中間操作有惰性求值的效果:
List<Student> students = Arrays.asList(new Student("張三", 100), new Student("李四", 200), new Student("王五", 300));
students.stream().map(s -> {
System.out.println("惰性求值不會執行");
return s.getName();
});
students.stream().map(s -> {
System.out.println("有終止操作了會執行");
return s.getName();
}).forEach(System.out::println);
四、方法參考
jdk1.8的語法糖,只要Lambda 中 傳遞的引數 是方法參考中 的那個方法可以接收的型別 就可以使用方法參考,方法參考使用::雙冒號表示,可以省略引數及方法的形參,就是可推倒就可省略,方法參考的規定,實作抽象方法的引數串列,必須與方法參考方法的引數串列保持一致!至于回傳值就不作要求,
4.1 參考普通方法
public class Test {
private static void printString(Printable lambda) {
lambda.print("Hello");
}
public static void main(String[] args) {
Demo04MethodRef obj = new Demo04MethodRef();
printString(obj::printUpperCase);
printString(s->obj.printUpperCase(s));
}
}
@FunctionalInterface
interface Printable {
void print(String str);
}
class Demo04MethodRef {
public void printUpperCase(String str) {
System.out.println(str.toUpperCase());
}
}
4.2 參考靜態方法
@FunctionalInterface
public interface Calcable {
int calc(int num);
}
//第一種寫法是使用Lambda運算式:
public class Demo05Lambda {
private static void method(int num, Calcable lambda) {
System.out.println(lambda.calc(num));
}
public static void main(String[] args) {
method(‐10, n ‐> Math.abs(n));
}
}
//但是使用方法參考的更好寫法是:
public class Demo06MethodRef {
private static void method(int num, Calcable lambda) {
System.out.println(lambda.calc(num));
}
public static void main(String[] args) {
method(‐10, Math::abs);
}
}
4.3 通過super/this參考成員方法
@FunctionalInterface
public interface Greetable {
void greet();
}
public class Human {
public void sayHello() {
System.out.println("Hello!");
}
}
public class Man extends Human {
@Override
public void sayHello() {
System.out.println("大家好,我是Man!");
}
//定義方法method,引數傳遞Greetable介面
public void method(Greetable g){
g.greet();
}
public void show(){
//呼叫method方法,使用Lambda運算式
method(()‐>{
//創建Human物件,呼叫sayHello方法
new Human().sayHello();
});
//簡化Lambda
method(()‐>new Human().sayHello());
//使用super關鍵字代替父類物件
method(()‐>super.sayHello());
//方法參考
method(super::sayHello);
}
}
4.4 類的構造器參考
由于構造器的名稱與類名完全一樣,并不固定,所以構造器參考使用 類名稱::new 的格式表示,首先是一個簡單的 Person 類:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
然后是用來創建 Person 物件的函式式介面:
public interface PersonBuilder {
Person buildPerson(String name);
}
要使用這個函式式介面,可以通過Lambda運算式:
public class Demo09Lambda {
public static void printName(String name, PersonBuilder builder) {
System.out.println(builder.buildPerson(name).getName());
}
public static void main(String[] args) {
printName("趙麗穎", name ‐> new Person(name));
}
}
但是通過構造器參考,有更好的寫法:
public class Demo10ConstructorRef {
public static void printName(String name, PersonBuilder builder) {
System.out.println(builder.buildPerson(name).getName());
}
public static void main(String[] args) {
printName("窩嫩蝶", Person::new);
}
}
4.5 參考陣列
// Function<Integer, int[]> fun = n -> new int[n];
Function<Integer, int[]> fun = int[]::new;
int[] arr = fun.apply(10);
Function<Integer, Integer[]> fun2 = Integer[]::new;
Integer[] arr2 = fun2.apply(10);
五、其他新特性
5.1 Optional
比較簡單,就不自己弄了,參考
jdk1.8新特性之Optional
5.2 日期函式
date、SimpleDateFormat、calendar:執行緒不安全
jdk8提供的日期類
5.2.1 LocalDate和LocalTime
LocalDate類表示一個具體的日期,但不包含具體時間,也不包含時區資訊,可以通過LocalDate的靜態方法of()創建一個實體,LocalDate也包含一些方法用來獲取年份,月份,天,星期幾等:
LocalDate localDate = LocalDate.of(2017, 1, 4); // 初始化一個日期:2017-01-04
int year = localDate.getYear(); // 年份:2017
Month month = localDate.getMonth(); // 月份:JANUARY
int dayOfMonth = localDate.getDayOfMonth(); // 月份中的第幾天:4
DayOfWeek dayOfWeek = localDate.getDayOfWeek(); // 一周的第幾天:WEDNESDAY
int length = localDate.lengthOfMonth(); // 月份的天數:31
boolean leapYear = localDate.isLeapYear(); // 是否為閏年:false
LocalDate.now(); //獲得當前日期
LocalTime和LocalDate類似,他們之間的區別在于LocalDate不包含具體時間,而LocalTime包含具體時間
5.2.2 LocalDateTime
LocalDateTime類是LocalDate和LocalTime的結合體,可以通過of()方法直接創建,也可以呼叫LocalDate的atTime()方法或LocalTime的atDate()方法將LocalDate或LocalTime合并成一個LocalDateTime
LocalDateTime ldt1 = LocalDateTime.of(2017, Month.JANUARY, 4, 17, 23, 52);
LocalDate localDate = LocalDate.of(2017, Month.JANUARY, 4);
LocalTime localTime = LocalTime.of(17, 23, 52);
LocalDateTime ldt2 = localDate.atTime(localTime);
LocalDate date = ldt1.toLocalDate();
LocalTime time = ldt1.toLocalTime();
//執行緒安全的日期轉換
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
String localTime = df.format(time);
LocalDateTime ldt = LocalDateTime.parse("2018-01-12 17:07:05",df);
System.out.println("LocalDateTime轉成String型別的時間:"+localTime);
System.out.println("String型別的時間轉成LocalDateTime:"+ldt);
//獲取秒數
Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
//獲取毫秒數
Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
//LocalDate轉Date
LocalDate nowLocalDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
//LocalDateTime轉Date
LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant());
//Date轉LocalDateTime(LocalDate)
Date date =newDate();
LocalDateTime localDateTime = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
LocalDate localDate = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDate();
//LocalDate轉時間戳
LocalDate localDate = LocalDate.now();
longtimestamp = localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
//LocalDateTime轉時間戳
LocalDateTime localDateTime = LocalDateTime.now();
longtimestamp = localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
//時間戳轉LocalDateTime(LocalDate)
longtimestamp = System.currentTimeMillis();
LocalDate localDate = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDate();
LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/299544.html
標籤:其他
上一篇:【JAVA SE】 反射機制
下一篇:spring依賴注入的4種方式
