本文爲翻譯文章,原文地址 這裏java
歡迎來到本人對於Java 8的系列介紹教程,本教程會引導你一步步領略最新的語法特性。經過一些簡單的代碼示例你便可以學到默認的接口方法、Lambda表達式、方法引用以及重複註解等等。本文的最後還提供了譬如Stream API之類的詳細的介紹。git
Java 8 容許咱們利用default關鍵字來向接口中添加非抽象的方法做爲默認方法。下面是一個小例子:github
interface Formula { double calculate(int a); default double sqrt(int a) { return Math.sqrt(a); } }
在接口Formula中,除了抽象方法calculate以外,還定義了一個默認的方法sqrt。實現類只須要實現抽象方法calculate,而sqrt方法能夠跟普通方法同樣調用。c#
Formula formula = new Formula() { @Override public double calculate(int a) { return sqrt(a * 100); } }; formula.calculate(100); // 100.0 formula.sqrt(16); // 4.0
首先以簡單的字符串排序爲例來展現:多線程
List<String> names = Arrays.asList("peter", "anna", "mike", "xenia"); Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } });
靜態的工具類方法Collections.sort
接受一個列表參數和一個比較器對象來對於指定列表中的元素進行排序。咱們經常須要建立匿名比較器而且將他們傳遞給排序方法。而Java 8中提供的一種更短的Lambda表達式的方法來完成該工做:併發
Collections.sort(names, (String a, String b) -> { return b.compareTo(a); });
能夠發現用如上的方法寫會更短而且更加的可讀,而且能夠更短:intellij-idea
Collections.sort(names, (String a, String b) -> b.compareTo(a));
這種寫法就徹底不須要{}
以及return
關鍵字,再進一步簡化的話,就變成了:app
names.sort((a, b) -> b.compareTo(a));
Lambda表達式是如何適配進Java現存的類型系統的呢?每一個Lambda表達式都會關聯到一個由接口肯定的給定的類型。這種所謂的函數式接口必須只能包含一個抽象方法,而每一個該類型的Lambda表達式都會關聯到這個抽象方法。不過因爲默認方法不是抽象的,所以能夠隨便添加幾個默認的方法到函數式接口中。咱們能夠將任意的接口做爲Lambda表達式使用,只要該接口僅含有一個抽象方法便可。爲了保證你的接口知足這個需求,應該添加@FunctionalInterface
這個註解。編譯器會在你打算向某個函數式接口中添加第二個抽象方法時候報錯。dom
//聲明 @FunctionalInterface interface Converter<F, T> { T convert(F from); } //使用 Converter<String, Integer> converter = (from) -> Integer.valueOf(from); Integer converted = converter.convert("123"); System.out.println(converted); // 123
上述的代碼可使用靜態方法引用而更加的簡化:ide
Converter<String, Integer> converter = Integer::valueOf; Integer converted = converter.convert("123"); System.out.println(converted); // 123
Java 8容許將方法或則構造器的引用經過::
關鍵字進行傳遞,上述的例子是演示瞭如何關聯一個靜態方法,不過咱們也能夠關聯一個對象方法:
class Something { String startsWith(String s) { return String.valueOf(s.charAt(0)); } }
Something something = new Something(); Converter<String, String> converter = something::startsWith; String converted = converter.convert("Java"); System.out.println(converted); // "J"
接下來看 ::
關鍵字怎麼在構造器中起做用。首先咱們定義一個有兩個不一樣控制器的Java Bean:
class Person { String firstName; String lastName; Person() {} Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }
而後,咱們建立一個特定的Person工廠接口來建立新的Person對象:
interface PersonFactory<P extends Person> { P create(String firstName, String lastName); }
不須要手動的去繼承實現該工廠接口,咱們只須要將控制器的引用傳遞給該接口對象就行了:
PersonFactory<Person> personFactory = Person::new; Person person = personFactory.create("Peter", "Parker");
Java的控制器會自動選擇合適的構造器方法。
從Lambda表達式中訪問外部做用域中變量很是相似於匿名對象,能夠訪問本地的final變量、實例域以及靜態變量。
在匿名對象中,咱們能夠從Lambda表達式的域中訪問外部的final變量。
final int num = 1; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert(2); // 3
可是不一樣於匿名對象只能訪問final變量,Lambda表達式中能夠訪問final變量:
int num = 1; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert(2); // 3
不過須要注意的是,儘管變量不須要聲明爲final
,可是也是隱式的不可變:
int num = 1; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); num = 3;
譬如如上的寫法就會被報錯。
不一樣於本地變量,咱們能夠在Lambda表達式中任意的讀寫:
class Lambda4 { static int outerStaticNum; int outerNum; void testScopes() { Converter<Integer, String> stringConverter1 = (from) -> { outerNum = 23; return String.valueOf(from); }; Converter<Integer, String> stringConverter2 = (from) -> { outerStaticNum = 72; return String.valueOf(from); }; } }
注意,Lambda表達式中是不能夠訪問默認方法的:
Formula formula = (a) -> sqrt( a * 100);
上述代碼是編譯通不過的。
JDK 1.8 的API中包含了許多的內建的函數式接口,其中部分的譬如Comparator、Runnable被改寫成了能夠由Lambda表達式支持的方式。除此以外,Java 8還添加了許多來自於Guava中的依賴庫,並將其改造爲了Lambda接口。
Predicates是包含一個參數的返回爲布爾值的接口,接口包含了許多的默認方法來進行不一樣的複雜的邏輯組合:
Predicate<String> predicate = (s) -> s.length() > 0; predicate.test("foo"); // true 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();
Functions接口接受一個參數而且產生一個結果,一樣提供了部分默認的方法來鏈式組合不一樣的函數(compose,andThen)。
Function<String, Integer> toInteger = Integer::valueOf; Function<String, String> backToString = toInteger.andThen(String::valueOf); backToString.apply("123"); // "123"
Supplier<Person> personSupplier = Person::new; personSupplier.get(); // new Person
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName); greeter.accept(new Person("Luke", "Skywalker"));
Comparators相似於舊版本中的用法,Java 8是添加了一些默認的用法。
Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); Person p1 = new Person("John", "Doe"); Person p2 = new Person("Alice", "Wonderland"); comparator.compare(p1, p2); // > 0 comparator.reversed().compare(p1, p2); // < 0
Optionals並非一個函數式接口,可是很是有用的工具類來防止NullPointerException
。Optional是一個簡單的容器用於存放那些可能爲空的值。對於那種可能返回爲null的方法能夠考慮返回Optional而不是null:
Optional<String> optional = Optional.of("bam"); optional.isPresent(); // true optional.get(); // "bam" optional.orElse("fallback"); // "bam" optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b"
一個Java的Stream對象表明了一系列能夠被附加多個操做的元素的序列集合。經常使用的Stream API分爲媒介操做與終止操做。其中終止操做會返回某個特定類型的值,而媒介操做則會返回流自己以方便下一步的鏈式操做。Streams能夠從java.util.Collection
的數據類型譬如lists或者sets(不支持maps)中建立。而Streams的操做能夠順序執行也能夠併發地執行。
Stream.js是一個利用JavaScript實現的Java 8的流接口。
首先咱們建立待處理的數據:
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");
接下來能夠利用Collection.stream()
or Collection.parallelStream()
來轉化爲一個流對象。
Filter會接受一個Predicate對象來過濾流中的元素,這個操做屬於媒介操做,譬如能夠在該操做以後調用另外一個流操做(forEach
)。ForEach操做屬於終止操做,接受一個Consumer對象來對於過濾以後的流中的每個元素進行操做。
stringCollection .stream() .filter((s) -> s.startsWith("a")) .forEach(System.out::println); // "aaa2", "aaa1"
Sorted操做屬於一個媒介操做,會將流對象做爲返回值返回。元素會默認按照天然的順序返回,除非你傳入了一個自定義的Comparator
對象。
stringCollection .stream() .sorted() .filter((s) -> s.startsWith("a")) .forEach(System.out::println); // "aaa1", "aaa2"
須要記住的是,Sorted操做並不會改變流中的元素的順序,只會建立一個通過排序的視圖,譬如:
System.out.println(stringCollection); // ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1
map
操做也是媒介操做的一種,能夠經過給定的函數將每一個元素映射到其餘對象。下面的代碼示例就是將全部的字符串轉化爲大寫字符串。不過map
操做是能夠將任意對象轉化爲任意類型,流返回的泛型類型取決於傳遞給map
的函數的返回值。
stringCollection .stream() .map(String::toUpperCase) .sorted((a, b) -> b.compareTo(a)) .forEach(System.out::println); // "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1"
Java 8提供了一些列的匹配的終止操做符來幫助開發者判斷流當中的元素是否符合某些判斷規則。全部的匹配類型的操做都會返回布爾類型。
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
Count 也是終止操做的一種,它會返回流中的元素的數目。
long startsWithB = stringCollection .stream() .filter((s) -> s.startsWith("b")) .count(); System.out.println(startsWithB); // 3
該操做根據指定的方程對於流中的元素進行了指定的減小的操做。結果是Optional
類型。
Optional<String> reduced = stringCollection .stream() .sorted() .reduce((s1, s2) -> s1 + "#" + s2); reduced.ifPresent(System.out::println); // "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2"
正如上文中說起的,流能夠是順序的也能夠是並行的。全部在順序流上執行的流操做都是在單線程中運行的,而在並行流中進行的操做都是在多線程中運行的。以下的代碼演示瞭如何利用並行流來提供性能,首先咱們建立一個待比較的序列:
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)); // sequential sort took: 899 ms
long t0 = System.nanoTime(); long count = values.parallelStream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("parallel sort took: %d ms", millis)); // parallel sort took: 472 ms
正如上文所說,Map並不支持流操做,可是也提供了不少有用的方法來進行通用的操做。
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));
上述的代碼中,putIfAbsent
避免了寫太多額外的空檢查。forEach
會接受一個Consumer參數來遍歷Map中的元素。下面的代碼演示如何進行計算:
map.computeIfPresent(3, (num, val) -> val + num); map.get(3); // val33 map.computeIfPresent(9, (num, val) -> null); map.containsKey(9); // false map.computeIfAbsent(23, num -> "val" + num); map.containsKey(23); // true map.computeIfAbsent(3, num -> "bam"); map.get(3); // val33
還有,Map提供瞭如何根據給定的key,vaue來刪除Map中給定的元素:
map.remove(3, "val3"); map.get(3); // val33 map.remove(3, "val33"); map.get(3); // null
還有一個比較有用的方法:
map.getOrDefault(42, "not found"); // not found
同時,Map還提供了merge方法來幫助有效地對於值進行修正:
map.merge(9, "val9", (value, newValue) -> value.concat(newValue)); map.get(9); // val9 map.merge(9, "concat", (value, newValue) -> value.concat(newValue)); map.get(9); // val9concat
Java 8包含了一個全新的日期與時間的API,在java.time
包下,新的時間API集成了Joda-Time
的庫。
Clock方便咱們去讀取當前的日期與時間。Clocks能夠根據不一樣的時區來進行建立,而且能夠做爲System.currentTimeMillis()
的替代。這種指向時間軸的對象便是Instant
類。Instants能夠被用於建立java.util.Date
對象。
Clock clock = Clock.systemDefaultZone(); long millis = clock.millis(); Instant instant = clock.instant(); Date legacyDate = Date.from(instant); // legacy java.util.Date
Timezones以ZoneId
來區分。能夠經過靜態構造方法很容易的建立,Timezones定義了Instants與Local Dates之間的轉化關係:
System.out.println(ZoneId.getAvailableZoneIds()); // prints all available timezone ids ZoneId zone1 = ZoneId.of("Europe/Berlin"); ZoneId zone2 = ZoneId.of("Brazil/East"); System.out.println(zone1.getRules()); System.out.println(zone2.getRules()); // ZoneRules[currentStandardOffset=+01:00] // ZoneRules[currentStandardOffset=-03:00]
LocalTime表明了一個與時間無關的本地時間,譬如 10pm 或者 17:30:15。下述的代碼展現了根據不一樣的時間軸建立的不一樣的本地時間:
LocalTime now1 = LocalTime.now(zone1); LocalTime now2 = LocalTime.now(zone2); 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提供了不少的工廠方法來簡化建立實例的步驟,以及對於時間字符串的解析:
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
LocalDate表明了一個獨立的時間類型,譬如2014-03-11。它是一個不可變的對象而且很相似於LocalTime。下列代碼展現瞭如何經過增減時間年月來計算日期:
LocalDate today = LocalDate.now(); LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS); LocalDate yesterday = tomorrow.minusDays(2); LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4); DayOfWeek dayOfWeek = independenceDay.getDayOfWeek(); System.out.println(dayOfWeek); // FRIDAY
從字符串解析獲得LocalDate對象也像LocalTime同樣簡單:
DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedDate(FormatStyle.MEDIUM) .withLocale(Locale.GERMAN); LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter); System.out.println(xmas); // 2014-12-24
LocalDateTime表明了時間日期類型,它組合了上文提到的Date類型以及Time類型。LocalDateTime一樣也是一種不可變類型,很相似於LocalTime以及LocalDate。
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 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
Java 8中的註解如今是能夠重複的,下面咱們用例子直接說明。首先,建立一個容器註解能夠用來存儲一系列真實的註解:
@interface Hints { Hint[] value(); } @Repeatable(Hints.class) @interface Hint { String value(); }
經過添加 @Repeatable
註解,就能夠在同一個類型中使用多個註解。
@Hints({@Hint("hint1"), @Hint("hint2")}) class Person {}
@Hint("hint1") @Hint("hint2") class Person {}
Hint hint = Person.class.getAnnotation(Hint.class); System.out.println(hint); // null Hints hints1 = Person.class.getAnnotation(Hints.class); System.out.println(hints1.value().length); // 2 Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class); System.out.println(hints2.length); // 2