2. JDK11 語法
2.0 var
var 型別推斷
@Test
public void t1() {
Consumer<String> c1 = t -> System.out.println(t.toUpperCase());
Consumer<String> c2 = (var t) -> System.out.println(t.toUpperCase());
c2.accept("a");
// 錯誤的形式: 必須要有型別, 可以加上var
// Consumer<String> c3 = (@Deprecated t) -> System.out.println(t.toUpperCase());
// 正確的形式:
Consumer<String> c3 = (@Deprecated var t) -> System.out.println(t.toUpperCase());
}
2.1 Stream
2.1.1 Stream.ofNullable 對null的過濾
@Test
public void t1(){
// 傳入null會被解析成一個陣列物件,會進一步訪問他的長度資訊,故不安全,null時會拋異常
Stream<Object> s1 = Stream.of(null);
s1.forEach(System.out::println);
// 傳入一個null,使用流物件進行檢測,如果是null,則過濾掉
Stream<Object> s2 = Stream.ofNullable(null);
s2.forEach(System.out::println);
}
2.1.2 takeWhile() 與 dropWhile()
@Test
public void t2(){
Stream<Integer> stream1 = Stream.of(1, 1, 3, 2, 2, 3, 4, 5);
// takeWhile:一直拿(條件為True),拿不到(條件為False)則終止
// 取奇數 1 1 3,2不是奇數,所以到2就停止了
Stream<Integer> stream2 = stream1.takeWhile(t -> t % 2 != 0);
stream2.forEach(i->log.info("no1:" + i));
log.info("---");
// dropWhile:一直拋棄(條件為True),(條件為False)不再拋棄才開始拿
// 1 1 3 都是奇數,都要拋棄,2不是奇數,從2開始一直拿
stream1 = Stream.of(1, 1, 3, 2, 2, 3, 4, 5);
stream2 = stream1.dropWhile(t -> t % 2 != 0);
stream2.forEach(i->log.info("no2:" + i));
}
輸出:
01:09:00.924 [main] INFO com.lee.jdk11.study.sgg.StreamTest - no1:1
01:09:00.926 [main] INFO com.lee.jdk11.study.sgg.StreamTest - no1:1
01:09:00.926 [main] INFO com.lee.jdk11.study.sgg.StreamTest - no1:3
01:09:00.926 [main] INFO com.lee.jdk11.study.sgg.StreamTest - ---
01:09:00.928 [main] INFO com.lee.jdk11.study.sgg.StreamTest - no2:2
01:09:00.928 [main] INFO com.lee.jdk11.study.sgg.StreamTest - no2:2
01:09:00.928 [main] INFO com.lee.jdk11.study.sgg.StreamTest - no2:3
01:09:00.929 [main] INFO com.lee.jdk11.study.sgg.StreamTest - no2:4
01:09:00.930 [main] INFO com.lee.jdk11.study.sgg.StreamTest - no2:5
本作品採用《CC 協議》,轉載必須註明作者和本文連結