JDK1.8+新特性
1、介面的預設方法————>defaultmethod
public interface DefaultMethodInterface { /** * @param str */ public void printString(String str); /** * @return */ public default String defaultPrint() { System.out.println("介面預設方法已呼叫"); return "介面預設方法已呼叫"; } }
public class DefaultMethodInterfaceImpl implements DefaultMethodInterface { private static final DefaultMethodInterface dmi = new DefaultMethodInterfaceImpl(); private DefaultMethodInterfaceImpl() { } public static DefaultMethodInterface getInstance() { return dmi; } @Override public void printString(String str) { System.out.println("介面預設方法呼叫前..."); this.defaultPrint(); System.out.println("介面預設方法呼叫後..."); } public static void main(String[] args) { DefaultMethodInterfaceImpl.getInstance().printString("hello,interface default method..."); }}
2、介面的靜態方法————>staticmethod
public interface A { public static String a(String a) { return a; } }
public class Client { public static void main(String[] args) { System.out.println(A.a("介面靜態方法!")); }}
3、Lambda表示式————>lambda
public interface MyInterface { public void print(String str); }public interface MyInterface2 { public void print2(String str1,String str2); }public class MyInterfaceUse { public void use(MyInterface myInterface,String str) { myInterface.print(str); } }public class MyInterfaceUse2 { public void use(MyInterface2 myInterface2, String str) { myInterface2.print2(str, str); }}public class MyRunnable implements Runnable { @Override public void run() { String threadName = Thread.currentThread().getName(); System.out.println(threadName + ",my running..."); }}
public class Client01 { public static void main(String[] args) { // 1、普通執行緒 new Thread(new MyRunnable(), "執行緒1").start(); // 2、lambda的使用 new Thread(() -> { System.out.println("方式1:使用lambda!"); }).start(); new Thread(() -> System.out.println("方式2:使用lambda!")).start(); // 3、自定義介面使用lambda new MyInterfaceUse().use(s -> { System.out.println(s); }, "方式1:自定義介面使用lambda!"); new MyInterfaceUse().use((s) -> { System.out.println(s); }, "方式2:自定義介面使用lambda!"); new MyInterfaceUse().use(s -> System.out.println(s), "方式3:自定義介面使用lambda!"); // 4、自定義介面使用lambda new MyInterfaceUse2().use((str1, str2) -> System.out.println(str1 + " | " + str2), "方式1:lambda表示式"); new MyInterfaceUse2().use((str1, str2) -> { System.out.println(str1 + " | " + str2); }, "方式2:lambda表示式"); }}
public class Client02 { public static void main(String[] args) { // 古老的方式 List<String> arrayList = new ArrayList<String>(); arrayList.add("aaaaa"); arrayList.add("bbbbb"); arrayList.add("ccccc"); arrayList.add("ddddd"); arrayList.add("eeeee"); for (String str : arrayList) { System.out.println(str); } System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // 新方式 List<String> arrayList2 = Arrays.asList("aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"); arrayList2.forEach(str -> System.out.println(str)); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); arrayList2.forEach(str -> { System.out.println(str); }); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); arrayList2.forEach((str) -> { System.out.println(str); }); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // Set<String> hashSet = new HashSet<String>(); hashSet.add("aaaaa"); hashSet.add("bbbbb"); hashSet.add("ccccc"); hashSet.forEach(str -> System.out.println(str)); hashSet.forEach(str -> { System.out.println(str); }); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); hashSet.forEach(str -> { System.out.println(str); System.out.println(str); }); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); Map<String, String> hashMap = new HashMap<String, String>(); hashMap.put("aaaaa", "aaaaa"); hashMap.put("bbbbb", "bbbbb"); hashMap.put("ccccc", "ccccc"); hashMap.forEach((k, v) -> { System.out.println(k + "====>" + v); }); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); /** * forEach方法提供者:List、Set、Map */ }}
4、函式式介面————>functional
public class FunctionalMain01 { public static void main(String[] args) { Converter<String, Integer> converter = (from) -> Integer.valueOf(from); Integer converted = converter.convert("1234"); System.out.println(converted); // 1234 } @FunctionalInterface interface Converter<F, T> { T convert(F from); } }
@FunctionalInterfacepublic interface Converter<I1,I2> { /** * 比較2個數 * * @param i1 * @param i2 * @return */ public boolean convert(I1 i1,I2 i2); }
public class FunctionalIntefaceDemo { public static void main(String[] args) { // 函式式介面,比較2個數的大小 Converter<Integer, Integer> converter = (i1, i2) -> { return i1 > i2; }; System.out.println(converter.convert(1, 2)); // 函式式介面 Converter<Integer, Integer> converter2 = (i1, i2) -> { return i2 > i1; }; System.out.println(converter2.convert(1, 2)); // 函式式介面註解====》 @FunctionalInterface }}
5、方法與建構函式引用————>methodref
public class User { private int id; private String name; public User(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User [id=" + id + ", name=" + name + "]"; } }
public interface UserFactory<P extends Object> { P create(int id, String name);}
public class ClientMain { public static void main(String[] args) { String[] strArray = { "a", "c", "b" }; // 排序 Arrays.sort(strArray, (s1, s2) -> s1.compareTo(s2)); // 方法引用 Arrays.sort(strArray, String::compareTo); for (String str : strArray) { System.out.print(str + " "); } System.out.println(); User user = new User(1, "張三"); Supplier<Integer> idSupplier = () -> user.getId(); Supplier<String> nameSupplier = () -> user.getName(); System.out.println("id=" + idSupplier.get() + ",name=" + nameSupplier.get()); // 方法引用 Supplier<Integer> idSupplier2 = user::getId; Supplier<String> nameSupplier2 = user::getName; System.out.println("id=" + idSupplier2.get() + ",name=" + nameSupplier2.get()); // ======================================// UserFactory<User> userFactory = new UserFactory<User>() { @Override public User create(int id, String name) { return new User(id,name); } }; System.out.println(userFactory.create(2, "李四").toString()); // lambda表示式 UserFactory<User> userFactory2 = (id,name) -> {return new User(id,name);}; System.out.println(userFactory2.create(2, "李四").toString()); // 方法引用 UserFactory<User> userFactory3 = User::new; System.out.println(userFactory3.create(2, "李四").toString()); }}
public class MethodReferencesMain { public static void main(String[] args) { String[] strArray = { "a", "c", "b" }; // 使用Lambda表示式比較 Arrays.parallelSort(strArray, (s1, s2) -> { return s2.hashCode() - s1.hashCode(); }); for (String str : strArray) { System.out.print(str + " "); } System.out.println(" "); // ============================================================================// // 介面:java.lang.Comparable<T> 方法:public int compareTo(T o); // 傳入值:java.lang.String,方法: public int compareTo(String anotherString); // ============================================================================// Arrays.parallelSort(strArray, String::compareTo); for (String str : strArray) { System.out.print(str + " "); } System.out.println(" "); }}
6、常用函式式介面————>optional
1、Supplier, 你要作為一個供應者,自己生產資料;
2、Consumer, 你要作為一個消費者,利用已經準備資料;
3、Function, 輸入一個或者兩個不同或者相同的值轉為另一個值;
4、Predicate, 輸入一個或者兩個不同或者相同的值總是輸出boolean;
5、UnaryOperator, 輸入一個值轉換為相同值輸出;
6、BinaryOperator, 輸入兩個相同型別的值 轉為相同型別的值輸出;
public class Person { int id; String name; public Person() { super(); } public Person(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class SupplierMain { public static void main(String[] args) { // Supplier=====>get Supplier<Person> personSupplier = Person::new; System.out.println("create Person : " + personSupplier.get()); }}
public class ConsumerMain { public static void main(String[] args) { // Consumer=====>accept Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.getId() + "," + p.getName()); greeter.accept(new Person(1111, "Luke")); }}
public class FunctionMain { public static void main(String[] args) { // Function=====>apply Function<String, Integer> toInteger = Integer::valueOf; Function<String, String> backToString = toInteger.andThen(String::valueOf); System.out.println(backToString.apply("123")); }}
public class PredicateMain { public static void main(String[] args) { // Predicate=====>test Predicate<String> predicate = (s) -> (s.length() > 0); System.out.println(predicate.test("foo")); // true System.out.println(predicate.negate().test("foo")); // false Predicate<Boolean> nonNull = Objects::nonNull; Predicate<Boolean> isNull = Objects::isNull; Predicate<String> isEmpty = String::isEmpty; Predicate<String> isNotEmpty = isEmpty.negate(); System.out.println(nonNull.test(null)); System.out.println(isNull.test(null)); System.out.println(isEmpty.test("")); System.out.println(isNotEmpty.test("")); }}
public class ComparatorMain { public static void main(String[] args) { // Comparator=====>compare Comparator<Person> comparator1 = (p1, p2) -> p2.id - p1.id; Comparator<Person> comparator2 = (p1, p2) -> p2.name.compareTo(p1.name); Person p1 = new Person(1, "Doe"); Person p2 = new Person(2, "Wonderland"); System.out.println(comparator1.compare(p1, p2)); // > 0 // 反轉比較 System.out.println(comparator1.reversed().compare(p1, p2));// < 0 System.out.println(comparator2.compare(p1, p2)); // > 0 System.out.println(comparator2.reversed().compare(p1, p2));// < 0 }}
public class OptionalMain { public static void main(String[] args) { // Optional Optional<String> optional = Optional.of("bam"); System.out.println(optional.isPresent()); System.out.println(optional.get()); // "bam" System.out.println(optional.orElse("fallback")); // "bam" optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b" }}
7、Stream介面————>stream
package com.what21.jdk18.stream.case01.case01;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.UUID;import java.util.concurrent.TimeUnit;public class StreamMain { public static void main(String[] args) { List<String> stringCollection = new ArrayList<>(); stringCollection.add("ddd2"); stringCollection.add("aaa2"); stringCollection.add("bbb1"); stringCollection.add("aaa1"); stringCollection.add("bbb3"); stringCollection.add("ccc"); stringCollection.add("bbb2"); stringCollection.add("ddd1"); // Filter 過濾 stringCollection.stream().filter((s) -> s.startsWith("a")).forEach(System.out::println); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // Sort 排序 stringCollection.stream().sorted().filter((s) -> s.startsWith("a")).forEach(System.out::println); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // Map 對映 stringCollection.stream().map(String::toUpperCase).sorted((a, b) -> a.compareTo(b)) .forEach(System.out::println); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // Match 匹配 boolean anyStartsWithA = stringCollection.stream().anyMatch((s) -> s.startsWith("a")); System.out.println(anyStartsWithA); // 有一個匹配:true boolean allStartsWithA = stringCollection.stream().allMatch((s) -> s.startsWith("a")); System.out.println(allStartsWithA); // 所有的匹配:false boolean noneStartsWithZ = stringCollection.stream().noneMatch((s) -> s.startsWith("z")); System.out.println(noneStartsWithZ); // 沒有一個匹配:true System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // Count 計數 long startsWithB = stringCollection.stream().filter((s) -> s.startsWith("b")).count(); System.out.println(startsWithB); // 3 // Reduce 規約 Optional<String> reduced = stringCollection.stream().sorted().reduce((s1, s2) -> s1 + "#" + s2); reduced.ifPresent(System.out::println); // aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2 System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); // 並行Streams int max = 1000000; List<String> values = new ArrayList<>(max); for (int i = 0; i < max; i++) { UUID uuid = UUID.randomUUID(); values.add(uuid.toString()); } // 序列排序 long t0 = System.nanoTime(); long count = values.stream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("sequential sort took: %d ms", millis)); // 並行排序 long t3 = System.nanoTime(); long count2 = values.parallelStream().sorted().count(); System.out.println(count2); long t4 = System.nanoTime(); long millis2 = TimeUnit.NANOSECONDS.toMillis(t4 - t3); System.out.println(String.format("parallel sort took: %d ms", millis2)); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); System.out.println(">>>>>>>>>>>>>Map"); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i); } map.forEach((id, val) -> System.out.println(val)); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); map.computeIfPresent(3, (num, val) -> val + num); System.out.println(map.get(3)); // val33 System.out.println(map.computeIfPresent(9, (num, val) -> null)); System.out.println(map.containsKey(9)); // false System.out.println(map.computeIfAbsent(23, num -> "val" + num)); System.out.println(map.containsKey(23)); // true System.out.println(map.computeIfAbsent(3, num -> "bam")); System.out.println(map.get(3)); // val33 System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); System.out.println(map.remove(3, "val3")); System.out.println(map.get(3)); // val33 System.out.println(map.remove(3, "val33")); System.out.println(map.get(3)); // null System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); System.out.println(map.getOrDefault(42, "not found")); System.out.println(map.merge(9, "val9", (value, newValue) -> value.concat(newValue))); System.out.println(map.get(9)); // val9 System.out.println(map.merge(9, "concat", (value, newValue) -> value.concat(newValue))); System.out.println(map.get(9)); // val9concat }}
8、base64————>base64
package com.what21.jdk18.base64.case01.mode01;import java.util.Base64;import java.util.Base64.Decoder;import java.util.Base64.Encoder;public class Base64Main { public static void main(String[] args) { Encoder encoder = Base64.getEncoder(); byte[] str = encoder.encode("學習中...".getBytes()); System.out.println(str); Decoder decoder = Base64.getDecoder(); System.out.println(new String(decoder.decode(str))); }}
9、datetime————>datetime
import java.time.Clock;import java.time.Instant;import java.util.Date;// Clock 時鐘public class ClockMain { public static void main(String[] args) { // Clock clock = Clock.systemDefaultZone(); long millis = clock.millis(); System.out.println("millis=" + millis); Instant instant = clock.instant(); // 將Instannt Date legacyDate = Date.from(instant); System.out.println("data=" + legacyDate); }}
import java.time.DayOfWeek;import java.time.LocalDate;import java.time.Month;import java.time.format.DateTimeFormatter;import java.time.format.FormatStyle;import java.time.temporal.ChronoUnit;import java.util.Locale;// LocalDate 本地日期public class LocalDateMain { public static void main(String[] args) { LocalDate today = LocalDate.now(); LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS); LocalDate yesterday = tomorrow.minusDays(2); System.out.println(yesterday); LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4); DayOfWeek dayOfWeek = independenceDay.getDayOfWeek(); System.out.println(dayOfWeek); // FRIDAY DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) .withLocale(Locale.GERMAN); LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter); System.out.println(xmas); // 2014-12-24 }}
import java.time.DayOfWeek;import java.time.Instant;import java.time.LocalDateTime;import java.time.Month;import java.time.ZoneId;import java.time.format.DateTimeFormatter;import java.time.temporal.ChronoField;import java.util.Date;public class LocalDateTimeMain { public static void main(String[] args) { LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59); DayOfWeek dayOfWeek = sylvester.getDayOfWeek(); System.out.println(dayOfWeek); // WEDNESDAY Month month = sylvester.getMonth(); System.out.println(month); // DECEMBER long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY); System.out.println(minuteOfDay); // 1439 Instant instant = sylvester.atZone(ZoneId.systemDefault()).toInstant(); Date legacyDate = Date.from(instant); System.out.println(legacyDate); // Wed Dec 31 23:59:59 CET 2014 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy - HH:mm"); LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter); String string = formatter.format(parsed); System.out.println(string); // Nov 03, 2014 - 07:13 }}
import java.time.LocalTime;import java.time.ZoneId;import java.time.format.DateTimeFormatter;import java.time.format.FormatStyle;import java.time.temporal.ChronoUnit;import java.util.Locale;// LocalTime 本地時間public class LocalTimeMain { public static void main(String[] args) { ZoneId zone1 = ZoneId.of("Asia/Karachi"); ZoneId zone2 = ZoneId.of("Europe/Paris"); LocalTime now1 = LocalTime.now(zone1); LocalTime now2 = LocalTime.now(zone2); System.out.println(now1 + " " + now2); System.out.println(now1.isBefore(now2)); // false // 小時 long hoursBetween = ChronoUnit.HOURS.between(now1, now2); // 分鐘 long minutesBetween = ChronoUnit.MINUTES.between(now1, now2); System.out.println(hoursBetween); // -3 System.out.println(minutesBetween); // -239 LocalTime late = LocalTime.of(23, 59, 59); System.out.println(late); // 23:59:59 DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) .withLocale(Locale.GERMAN); LocalTime leetTime = LocalTime.parse("13:37", germanFormatter); System.out.println(leetTime); // 13:37 }}
import java.time.ZoneId;// Timezones 時區public class TimezonesMain { public static void main(String[] args) { // 可以取到的時區 System.out.println(ZoneId.getAvailableZoneIds()); ZoneId zone1 = ZoneId.of("Europe/Berlin"); ZoneId zone2 = ZoneId.of("Brazil/East"); System.out.println(zone1.getRules()); System.out.println(zone2.getRules()); }}
import java.time.Clock;import java.time.LocalDate;public class Java8DateTimeDemo { public static void main(String[] args) { // 獲取時鐘 Clock clock = Clock.systemDefaultZone(); System.out.println("系統時區:" + clock.getZone()); LocalDate localDate = LocalDate.now(clock); // 獲取當前時間(yyyy-MM-dd) System.out.println("當前日期:" + localDate); LocalDate localDate2 = LocalDate.of(2020, 8, 3); System.out.println("獲取日期:" + localDate2); }}
10、Nashorn引擎————>nashorn
var fun1 = function(name) { print('Hi there from Javascript, ' + name); return "greetings from javascript";};var fun2 = function (object) { print("JS Class Definition: " + Object.prototype.toString.call(object));};
import java.io.FileNotFoundException;import java.io.FileReader;import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;import javax.script.ScriptException;public class ScriptEngineMain { public static void main(String[] args) { ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); try { engine.eval("print('Hello World!');"); } catch (ScriptException e) { e.printStackTrace(); } ScriptEngine engine2 = new ScriptEngineManager().getEngineByName("nashorn"); try { engine2.eval(new FileReader("script.js")); } catch (FileNotFoundException | ScriptException e) { e.printStackTrace(); } }}
11、使用Metaspace————>metaspace
使用Metaspace(JEP 122)代替持久代(PermGen space)。
JVM引數:使用-XX:MetaSpaceSize和-XX:MaxMetaspaceSize代替原來的-XX:PermSize和-XX:MaxPermSize。
12、jdeps工具————>jdeps
類依賴分析器jdeps
jdeps 01.BasicKnowledge-0.0.1-SNAPSHOT.jarD:\Apps\Java\Jdk\jdk1.8.0_221\bin\jdeps.exe 01.BasicKnowledge-0.0.1-SNAPSHOT.jar01.BasicKnowledge-0.0.1-SNAPSHOT.jar -> D:\Apps\Java\Jdk\jdk1.8.0_221\jre\lib\rt.jar com.what21.jdk18.accessvar.case01.mode01 (01.BasicKnowledge-0.0.1-SNAPSHOT.jar) -> java.io -> java.lang -> java.lang.invoke com.what21.jdk18.base64.case01.mode01 (01.BasicKnowledge-0.0.1-SNAPSHOT.jar) -> java.io -> java.lang -> java.util com.what21.jdk18.datetime.case01.mode01 (01.BasicKnowledge-0.0.1-SNAPSHOT.jar) -> java.io -> java.lang -> java.time -> java.time.format -> java.time.temporal -> java.time.zone -> java.util com.what21.jdk18.defaultmethod.case01.mode01 (01.BasicKnowledge-0.0.1-SNAPSHOT.jar)
13、可重複註解————>repeatannotation
import java.lang.annotation.Repeatable;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Repeatable(Hints.class)@Retention(RetentionPolicy.RUNTIME)public @interface Hint { String value();}
import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)public @interface Hints { Hint[] value(); }
@Hint("hint1")@Hint("hint2")public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
@Hints({ @Hint("hint1"), @Hint("hint2") })public class Person2 { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; }}
public class Main { public static void main(String[] args) { Hint hint = Person.class.getAnnotation(Hint.class); System.out.println(hint); // null Hints hints1 = Person2.class.getAnnotation(Hints.class); System.out.println(hints1.value().length); // 2 Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class); System.out.println(hints2.length); // 2 }}