Java8:Lambda表达式加强版Comparator和排序

一、概述

在这篇教程里,咱们将要去了解下即将到来的JDK 8(译注,如今JDK 8已经发布了)中的Lambda表达式——特别是怎样使用它来编写Comparator和对集合(Collection)进行排序。html

这篇文章是Baeldung上的“Java ——回归基础”(“Java – Back to Basic”)系列的一部分。java

首先,让咱们先定义一个简单的实体类:git

1github

2ide

3函数

4测试

5this

6spa

7.net

8

9

10

11

12

13

14

15

16

17

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建立一个匿名内部类用来排序:

1

2

3

4

5

6

new Comparator<Human>() {

@Override

public int compare(Human h1, Human h2) {

return h1.getName().compareTo(h2.getName());

}

}

简单地用它来对Human实体列表进行排序:

1

2

3

4

5

6

7

8

9

10

11

@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表达式的介绍,咱们如今能够不使用匿名内部类,只使用简单实用的语义就能够获得相同的结果。

1

(final Human h1, final Human h2) -> h1.getName().compareTo(h2.getName());

相似地,咱们如今能够像以前那样来测试它的行为:

1

2

3

4

5

6

7

@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。

四、没有类型定义( Type Definitions)的基本排序

咱们经过不指定类型定义来进一步简化表达式 ——编译器本身能够进行类型判断

1

(h1, h2) -> h1.getName().compareTo(h2.getName())

测试仍然很类似:

1

2

3

4

5

6

7

@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表达式去进行排序。

首先,咱们要定义compareByNameThenAge方法 ——这个方法拥有与Comparator<Human>对象里的compareTo方法彻底相同的签名:

1

2

3

4

5

6

7

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方法:

1

humans.sort(Human::compareByNameThenAge);

最终结果是一个使用静态方法做为Comparator的有效的排序集合:

1

2

3

4

5

6

7

@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对列表进行排序:

1

2

3

4

5

6

7

@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)——咱们能够快速地利用它来反转咱们的排序:

1

2

3

4

5

6

7

8

9

@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来对实体进行排序:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@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)去建造更复杂的比较逻辑:

1

2

3

4

5

6

7

8

@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表达式对列表进行排序——正确使用过去的语法糖和真正、强大实用的语义。

全部这些例子的实现和代码片断均可以在个人github项目上获取到——这是一个基于Eclipse的项目,因此它应该很容易被导入和运行。

原文连接: baeldung 翻译: ImportNew.com 进林
译文连接: http://www.importnew.com/15259.html

相关文章
相关标签/搜索