閱讀919 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Java8簡明指南

Java8簡明指南

歡迎來到Java8簡明指南。本教程將一步一步指導你通過所有新語言特性。由短而簡單的代碼示例,帶你了解如何使用默認接口方法,lambda表達式,方法引用和可重複注解。本文的最後你會熟悉最新的API的變化如Stream,Fcuntional,Map API擴展和新的日期API。

 

接口的默認方法

在Java8中,利用default關鍵字使我們能夠添加非抽象方法實現的接口。此功能也被稱為擴展方法,這裏是我們的第一個例子:

interface Formula {
    double calculate(int a);

    default double sqrt(int a) {
        return Math.sqrt(a);
    }
}

除了接口抽象方法calculate,還定義了默認方法sqrt的返回值。具體類實現抽象方法calculate。默認的方法sqrt可以開箱即用。

Formula formula = new Formula() {
    @Override
    public double calculate(int a) {
        return sqrt(a * 100);
    }
};

formula.calculate(100);     // 100.0
formula.sqrt(16);           // 4.0

該公式被實現為匿名對象。這段代碼是相當長的:非常詳細的一個計算:6行代碼完成這樣一個簡單的計算。正如我們將在下一節中看到的,Java8有一個更好的方法來實現單方法對象。

Lambda表達式

讓我們以一個簡單的例子來開始,在以前的版本中對字符串進行排序:

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,為比較器的給定列表中的元素排序。你會發現自己經常創建匿名比較器並將它們傳遞給方法。

Java8支持更短的語法而不總是創建匿名對象,

Lambda表達式:

Collections.sort(names, (String a, String b) -> {
    return b.compareTo(a);
});

正如你可以看到的代碼更容易閱讀。但它甚至更短:

Collections.sort(names, (String a, String b) -> b.compareTo(a));

一行方法的方法體可以跳過{}和參數類型,使它變得更短:

Collections.sort(names, (a, b) -> b.compareTo(a));

Java編譯器知道參數類型,所以你可以跳過它們,接下來讓我們深入了解lambda表達式。

函數式接口(Functional Interfaces)

如何適應Java lambda表達式類型係統?每個lambda由一個指定的接口對應於一個給定的類型。所謂的函數式接口必須包含一個確切的一個抽象方法聲明。該類型將匹配這個抽象方法每個lambda表達式。因為默認的方法是不抽象的,你可以自由添加默認的方法到你的函數式接口。

我們可以使用任意的接口為lambda表達式,隻要接口隻包含一個抽象方法。確保你的接口滿足要求,你應該添加@FunctionalInterface注解。當你嚐試在接口上添加第二個抽象方法聲明時,編譯器會注意到這個注釋並拋出一個編譯器錯誤。

舉例:

@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

記住,有@FunctionalInterface注解的也是有效的代碼。

方法和構造函數引用

上麵的例子代碼可以進一步簡化,利用靜態方法引用:

Converter<String, Integer> converter = Integer::valueOf;
Integer converted = converter.convert("123");
System.out.println(converted);   // 123

Java使您可以通過::關鍵字調用引用的方法或構造函數。上麵的示例演示了如何引用靜態方法。但我們也可以參考對象方法:

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"

讓我們來看看如何使用::關鍵字調用構造函數。首先,我們定義一個Person類並且提供不同的構造函數:

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");

我們通過Person::new創建一個人的引用,Java編譯器會自動選擇正確的構造函數匹配PersonFactory.create的返回。

Lambda作用域

從lambda表達式訪問外部變量的作用域是匿名對象非常相似。您可以從本地外部範圍以及實例字段和靜態變量中訪問final變量。

訪問局部變量

我們可以從lambda表達式的外部範圍讀取final變量:

final int num = 1;
Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num);
stringConverter.convert(2);     // 3

但不同的匿名對象變量num沒有被聲明為final,下麵的代碼也有效:

int num = 1;
Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num);
stringConverter.convert(2);     // 3

然而num必須是隱含的final常量。以下代碼不編譯:

int num = 1;
Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num);
num = 3;

在lambda表達式裏修改num也是不允許的。

訪問字段和靜態變量

與局部變量不同,我們在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);
        };
    }
}

訪問默認接口方法

記得第一節的formula例子嗎?接口Formula定義了一個默認的方法可以從每個公式實例訪問包括匿名對象,

這並沒有Lambda表達式的工作。

默認方法不能在lambda表達式訪問。以下代碼不編譯:

Formula formula = (a) -> sqrt( a * 100);

內置函數式接口(Built-in Functional Interfaces)

JDK1.8的API包含許多內置的函數式接口。其中有些是眾所周知的,從舊版本中而來,如Comparator或者Runnable。使現有的接口通過@FunctionalInterface注解支持Lambda。

但是Java8 API也添加了新功能接口,使你的開發更簡單。其中一些接口是眾所周知的Google Guava庫。即使你熟悉這個庫也應該密切關注這些接口是如何延長一些有用的擴展方法。

Predicates(謂詞)

Predicates是一個返回布爾類型的函數。這就是謂詞函數,輸入一個對象,返回true或者false。

在Google Guava中,定義了Predicate接口,該接口包含一個帶有泛型參數的方法:

apply(T input): boolean
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(函數)

Functions接受一個參數,並產生一個結果。默認方法可以將多個函數串在一起(compse, andThen)

Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);

backToString.apply("123");     // "123"

Suppliers(生產者)

Suppliers產生一個給定的泛型類型的結果。與Functional不同的是Suppliers不接受輸入參數。

Supplier<Person> personSupplier = Person::new;
personSupplier.get();   // new Person

Consumers(消費者)

Consumers代表在一個單一的輸入參數上執行操作。

Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
greeter.accept(new Person("Luke", "Skywalker"));

Comparators(比較器)

Comparators在舊版本Java中是眾所周知的。Java8增加了各種默認方法的接口。

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(可選項)

Optionals是沒有函數的接口,取而代之的是防止NullPointerException異常。這是下一節的一個重要概念,所以讓我們看看如何結合Optionals工作。

Optional is a simple container for a value which may be null or non-null. Think of a method which may return a non-null result but sometimes return nothing. Instead of returning null you return an Optional in Java 8.

Optional是一個簡單的容器,這個值可能是空的或者非空的。考慮到一個方法可能會返回一個non-null的值,也可能返回一個空值。為了不直接返回null,我們在Java 8中就返回一個Optional。

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"

Streams(管道)

一個java.util.Stream代表一個序列的元素在其中的一個或多個可以執行的操作。流操作是中間或終端。當終端操作返回某一類型的結果時,中間操作返回流,這樣就可以將多個方法調用在一行中。流是一個源產生的,例如java.util.Collection像列表或設置(不支持map)。流操作可以被執行的順序或並行。

讓我們先看一下數據流如何工作。首先,我們創建一個字符串列表的數據:

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");

在Java8中Collections類的功能已經有所增強,你可用調用Collection.stream()Collection.parallelStream()

下麵的章節解釋最常見的流操作。

Filter

Filter接受一個predicate來過濾流的所有元素。這個中間操作能夠調用另一個流的操作(Foreach)的結果。ForEach接受一個消費者為每個元素執行過濾流。它是void,所以我們不能稱之為另一個流操作。

stringCollection
    .stream()
    .filter((s) -> s.startsWith("a"))
    .forEach(System.out::println);

// "aaa2", "aaa1"

Sorted

Sorted是一個中間操作,能夠返回一個排過序的流對象的視圖。這些元素按自然順序排序,除非你經過一個自定義比較器(實現Comparator接口)。

stringCollection
    .stream()
    .sorted()
    .filter((s) -> s.startsWith("a"))
    .forEach(System.out::println);

// "aaa1", "aaa2"

要記住,排序隻會創建一個流的排序視圖,而不處理支持集合的排序。原來string集合中的元素順序是沒有改變的。

System.out.println(stringCollection);
// ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1

Map

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"

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

Count

Count是一個終止操作返回流中的元素的數目,返回long類型。

long startsWithB =
    stringCollection
        .stream()
        .filter((s) -> s.startsWith("b"))
        .count();

System.out.println(startsWithB);    // 3

Reduce

該終止操作能夠通過某一個方法,對元素進行削減操作。該操作的結果會放在一個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"

Parallel 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());
}

現在我們測量一下流對這個集合進行排序消耗的時間。

Sequential Sort

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

Parallel Sort

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

你可以看到這兩段代碼片段幾乎是相同的,但並行排序大致是50%的差距。唯一的不同就是把stream()改成了parallelStream()

Map

正如前麵所說的Map不支持流操作,現在的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避免我們將null寫入;forEach接受一個消費者對象,從而將操作實施到每一個map中的值上。

這個例子演示了如何利用函數判斷或獲取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.remove(3, "val3");
map.get(3);             // val33

map.remove(3, "val33");
map.get(3);             // null

另一種實用的方法:

map.getOrDefault(42, "not found");  // not found

Map合並條目是非常容易的:

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

合並操作先看map中是否沒有特定的key/value存在,如果是,則把key/value存入map,否則merging函數就會被調用,對現有的數值進行修改。

Date API

Java8 包含一個新的日期和時間API,在java.time包下。新的日期API與Joda Time庫可以媲美,但它們是不一樣的。下麵的例子涵蓋了這個新的API最重要的部分。

Clock

Clock提供訪問當前日期和時間。Clock是對當前時區敏感的,可以用來代替System.currentTimeMillis()來獲取當前的毫秒值。當前時間線上的時刻可以用Instance類來表示。Instance可以用來創建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表示,通過靜態工廠方法可以很容易地訪問。時區還定義了一個偏移量,用來轉換當前時刻與目標時刻。

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

LocalTime代表沒有時區的時間,例如晚上10點或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

LocalDate

LocalDate代表一個唯一的日期,如2014-03-11。它是不可變的,完全模擬本地時間工作。此示例演示如何通過添加或減去天數,月數,年來計算新的日期。記住每一個操作都會返回一個新的實例。

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:

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

LocalDateTime代表日期時間。它結合了日期和時間見上麵的部分為一個實例。LocalDateTime是不可變的,類似於本地時間和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

隨著一個時區可以轉換為一個即時的附加信息。Instance可以被轉換為日期型轉化為指定格式的java.util.Date

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.text.NumberFormat,新的DateTimeFormatter是不可變的,線程安全的。

Annotations(注解)

在Java8中注解是可以重複的,讓我們深入到一個示例中。

首先,我們定義了一個包裝的注解,它擁有一個返回值為數組類型的方法Hint:

@interface Hints {
    Hint[] value();
}

@Repeatable(Hints.class)
@interface Hint {
    String value();
}

Java8使我們能夠使用相同類型的多個注解,通過@Repeatable聲明注解。

變體1:使用注解容器(老方法)
@Hints({@Hint("hint1"), @Hint("hint2")})
class Person {}
變體2:使用可重複注解(新方法)
@Hint("hint1")
@Hint("hint2")
class Person {}

使用變體2隱式編譯器隱式地設置了@Hints注解。這對於通過反射來讀取注解信息是非常重要的。

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

雖然在Person中從未定義@Hints注解,它仍然可讀通過getAnnotation(Hints.class)讀取。並且,getAnnotationsByType方法會更方便,因為它賦予了所有@Hints注解標注的方法直接的訪問權限。

@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
@interface MyAnnotation {}

歡迎Star我的開源Web框架Blade:https://github.com/biezhi/blade

最後更新:2017-05-22 13:31:45

  上一篇:go  Adopt Open JDK官方文檔(十)
  下一篇:go  Apache Velocity官方指南-總結