Java8-加強版Comparator和排序之Lambda表達式

一、概述

在這篇教程裏,咱們將要去了解下JAVA8中的Lambda表達式——特別是怎樣使用它來編寫Comparator和對集合(Collection)進行排序。java

首先,讓咱們先定義一個簡單的實體類:
bash

public class Human {
    private String name;
    private int age;

    public Human() {
        super();
    }

    public Human(final String name, final int age) {
        super();

        this.name = name;
        this.age = age;
    }

    // standard getters and setters
}複製代碼

二、不使用Lambda表達式的基本排序

在Java 8以前,對集合進行排序要爲Comparator建立一個匿名內部類用來排序:ide

new Comparator<Human>() {
    @Override
    public int compare(Human h1, Human h2) {
        return h1.getName().compareTo(h2.getName());
    }
}複製代碼

簡單地用它來對Human實體列表進行排序:函數

@Test
public void givenPreLambda_whenSortingEntitiesByName_thenCorrectlySorted() {
    List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
    Collections.sort(humans, new Comparator<Human>() {
        @Override
        public int compare(Human h1, Human h2) {
            return h1.getName().compareTo(h2.getName());
        }
    });
    Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}複製代碼

三、使用Lambda表達式的基本排序

根據Lambda表達式的介紹,咱們如今能夠不使用匿名內部類,只使用簡單實用的語義就能夠獲得相同的結果。測試

(final Human h1, final Human h2) -> h1.getName().compareTo(h2.getName());複製代碼

相似地,咱們如今能夠像以前那樣來測試它的行爲:大數據

@Test
public void whenSortingEntitiesByName_thenCorrectlySorted() {
    List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));

    humans.sort((Human h1, Human h2) -> h1.getName().compareTo(h2.getName()));
    Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}複製代碼

注意:咱們一樣使用新的sort API,這個API在Java 8裏被添加到java.util.List ——而不是舊的Collections.sort API。ui

四、沒有類型定義( Type Definitions)的基本排序

咱們經過不指定類型定義來進一步簡化表達式 ——編譯器本身能夠進行類型判斷this

(h1, h2) -> h1.getName().compareTo(h2.getName())複製代碼

測試仍然很類似:spa

@Test
public void givenLambdaShortForm_whenSortingEntitiesByName_thenCorrectlySorted() {
    List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));

    humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
    Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}複製代碼

五、使用靜態方法的引用來排序

下面咱們將要使用帶有靜態方法引用的Lambda表達式去進行排序。code

首先,咱們要定義compareByNameThenAge方法 ——這個方法擁有與Comparator對象裏的compareTo方法徹底相同的簽名:

public static int compareByNameThenAge(Human lhs, Human rhs) {
    if (lhs.name.equals(rhs.name)) {
        return lhs.age - rhs.age;
    } else {
        return lhs.name.compareTo(rhs.name);
    }
}複製代碼

如今,咱們要使用這個引用去調用humans.sort方法:

humans.sort(Human::compareByNameThenAge);複製代碼

最終結果是一個使用靜態方法做爲Comparator的有效的排序集合:

@Test
public void givenMethodDefinition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
    List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));

    humans.sort(Human::compareByNameThenAge);
    Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}複製代碼

六、提取Comparator進行排序

咱們能夠經過使用實例方法的引用和Comparator.comparing方法來避免定義比較邏輯——它會提取和建立一個基於那個函數的Comparable。

咱們準備使用getName() getter方法去建造Lambda表達式並經過name對列表進行排序:

@Test
public void givenInstanceMethod_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
    List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));

    Collections.sort(humans, Comparator.comparing(Human::getName));
    Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}複製代碼

七、反轉排序

JDK 8一樣提供了一個有用的方法用來反轉Comparator(reverse Comparator)——咱們能夠快速地利用它來反轉咱們的排序:

@Test
public void whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
    List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 10), new Human("Jack", 12));
    Comparator<Human> comparator = (h1, h2) -> h1.getName().compareTo(h2.getName());

    humans.sort(comparator.reversed());
    Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
}複製代碼

八、多條件排序

比較操做的Lambda表達式不必定都是這麼簡單的——咱們一樣能夠編寫更復雜的表達式,好比先根據name後根據age來對實體進行排序:

@Test
public void whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
    List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));

    humans.sort((lhs, rhs) -> {
        if (lhs.getName().equals(rhs.getName())) {
            return lhs.getAge() - rhs.getAge();
        } else {
            return lhs.getName().compareTo(rhs.getName());
        }
    });
    Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
}複製代碼

九、多條件組合排序

一樣的比較邏輯——先根據name進行排序其次是age,一樣能夠經過Comparator新的組合支持來實現。

從JDK 8開始,咱們如今能夠把多個Comparator鏈在一塊兒(chain together)去建造更復雜的比較邏輯:

@Test
public void givenComposition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
    List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));

    humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));
    Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
}複製代碼

十、總結

這篇文章舉例說明了多種使人興奮的方法:使用Java 8 Lambda表達式對列表進行排序——正確使用過去的語法糖和真正、強大實用的語義。

福利部分:

《從Java到大數據成神之路》

《幾百TJava和大數據資源下載》


相關文章
相關標籤/搜索