从零单排Java 8(3) —— List结合Lambdas对排序的高级用法

简介

在本教程中,咱们将首先了解Java 8中的Lambda支持,特别是如何利用它来编写Comparator并对Collection进行排序。java

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

public class Human {
    private String name;
    private int age;
}
复制代码

List的简单排序

在Java 8以前,对集合进行排序将涉及为排序中使用的Comparator建立匿名内部类:ide

new Comparator<Human>() {
    @Override
    public int compare(Human h1, Human h2) {
        return h1.getName().compareTo(h2.getName());
    }
}
复制代码

这个比较简单,我看看单元测试的案例:单元测试

@Test
public void givenPreLambda() {
    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在排序中的使用

随着Lambdas的引入,咱们如今能够绕过匿名内部类,并经过简单,功能的语义实现来获得相同的结果:测试

(final Human h1, final Human h2) -> h1.getName().compareTo(h2.getName());
复制代码

一样,仍是能够用以前的测试用例:ui

@Test
public void test() {
    List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 10), 
      new Human("Jack", 12)
    );
     
    humans.sort(
      (Human h1, Human h2) -> h1.getName().compareTo(h2.getName()));
  
    assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
复制代码

请注意,咱们还使用了添加到Java 8 中的java.util.List的新排序的API,而不是旧的Collections.sort API。spa

不带类型定义排序

咱们能够经过不指定类型定义来进一步简化表达式 - 编译器可以本身推断这些:code

(h1, h2) -> h1.getName().compareTo(h2.getName())
复制代码

测试用例以下:对象

@Test
public void test() {
     
    List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 10), 
      new Human("Jack", 12)
    );
     
    humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
  
    assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}

复制代码

这个得益于Lambda的方法支持,让个人代码更加简洁。排序

使用静态方法进行排序

接下来,咱们将使用Lambda Expression执行排序,并引用静态方法。

首先,咱们将定义方法compareByNameThenAgeComparator <Human>对象中的compare方法彻底相同返回值:

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(Human::compareByNameThenAge);
复制代码

看下单元测试

@Test
public void test() {
     
    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)));
}
复制代码

内部API的进行排序

咱们还能够经过使用Collections引用和Comparator.comparing方法组合进行排序比较。

咱们将使用getName()来构建Lambda表达式并按名称对List进行排序:

@Test
public void test() {
     
    List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 10), 
      new Human("Jack", 12)
    );
     
    Collections.sort(
      humans, Comparator.comparing(Human::getName));
    assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
复制代码

反向排序

Java 8还引入了一个用于反转比较器的辅助方法,咱们能够快速使用它来反转咱们的排序:

@Test
public void test() {
    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 test() {
    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)));
}
复制代码

多条件组合排序

相同的例子,咱们也能够经过Comparator的新组合支持来实现。

从JDK 8开始,咱们如今能够将多个比较器组合在一块儿,以构建更复杂的比较逻辑:

@Test
public void test() {
     
    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)));
}
复制代码

Stream排序

咱们还可使用Java 8的Stream sorted() API 对集合进行排序。

咱们可使用天然排序以及比较器提供的排序对stream进行排序。 为此,咱们有sorted(),与其对应的有两个API :

  • sorted();使用排序对Stream的元素进行排序,元素类必须实现Comparable接口
  • sorted(Comparator<? super T> comparator);根据Comparator实例对元素进行排序

让咱们看一个如何使用天然排序的sorted()方法的示例:

@Test
public final void test() {
    List<String> letters = Lists.newArrayList("B", "A", "C");
     
    List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
    assertThat(sortedLetters.get(0), equalTo("A"));
}
复制代码

如今让咱们看看咱们如何使用自定义Comparator与sorted():

@Test
public final void test() {   
    List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
    Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
     
    List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
    assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
复制代码

若是咱们使用Comparator.comparing()方法,咱们能够进一步简化上面的例子:

@Test
public final void test() {
    List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
  
    List<Human> sortedHumans = humans.stream()
      .sorted(Comparator.comparing(Human::getName))
      .collect(Collectors.toList());
       
    assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
复制代码

Stream反向排序

咱们也可使用Stream.sorted()来反向排序List。

首先,让咱们看一个如何将sorted()方法与Comparator.reverseOrder()组合以反向顺序对列表进行排序的示例:

@Test
public final void test() {
    List<String> letters = Lists.newArrayList("B", "A", "C");
 
    List<String> reverseSortedLetters = letters.stream()
      .sorted(Comparator.reverseOrder())
      .collect(Collectors.toList());
       
    assertThat(reverseSortedLetters.get(0), equalTo("C"));
}
复制代码

如今,让咱们看看如何使用sorted()方法和自定义Comparator:

@Test
public final void test() {
    List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
    Comparator<Human> reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName());
 
    List<Human> reverseSortedHumans = humans.stream().sorted(reverseNameComparator)
      .collect(Collectors.toList());
    assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
}

复制代码

最后,让咱们使用Comparator.comparing()方法简化上面的示例:

@Test
public final void test() {
    List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
 
    List<Human> reverseSortedHumans = humans.stream()
      .sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder()))
      .collect(Collectors.toList());
     
    assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
}
复制代码

总结

使用Java 8 Lambda表达式对List进行排序,效果是很是不错的,也是Lambda的使用场景之一,这一点展现了Lambda的强大的语义功能。

相关文章
相关标签/搜索