【JDK 8特性】让代码更优雅之List排序

先定义一个实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
}

下面的操做都基于这个类来进行操做。这里面使用了Lombok类库,它用注解的方式实现了基本的get和set等方法,让代码看起来更加的优雅。java

传统排序

在Java8以前,对集合排序只能建立一个匿名内部类ide

new Comparator<User>() {
    @Override
    public int compare(User h1, User h2) {
        return h1.getName().compareTo(h2.getName());
    }
}

下面是简单的对users进行排序(按名称正序)函数

@Test
public void testSortByName_with_plain_java() throws Exception {
   ArrayList<User> users = Lists.newArrayList(
           new User("shequ", 22),
           new User("leyuan", 25)
   );
   Collections.sort(users, new Comparator<User>() {
       public int compare(User h1, User h2) {
           return h1.getName().compareTo(h2.getName());
       }
   });
   Assert.assertThat(users.get(0), equalTo(new User("leyuan", 25)));
}

使用Lambda的List排序

使用JAVA8函数式方式的比较器code

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

下面是使用JAVA8函数式的比较的例子排序

@Test
public void testSortByName_with_lambda() throws Exception {
   ArrayList<User> users = Lists.newArrayList(
           new User("shequ", 22),
           new User("leyuan", 25)
   );
   users.sort((User h1, User h2) -> h1.getName().compareTo(h2.getName()));
   Assert.assertThat("shequ", equalTo(users.get(1).getName()));
}

没有类型定义的排序

对于上面的表达式还能够进行简化,JAVA编译器能够根据上下文推测出排序的类型:ip

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

简化后的比较器是这样的:get

@Test
public void testSortByNameSimplify_with_lambda() throws Exception {
   ArrayList<User> users = Lists.newArrayList(
           new User("shequ", 22),
           new User("leyuan", 25)
   );
   users.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
   Assert.assertThat("shequ", equalTo(users.get(1).getName()));
}

使用静态方法引用

JAVA8还能够提供使用Lambda表达式的静态类型引用,咱们在User类增长一个静态比较方法,以下:编译器

public static int compareByNameThenAge(User h1, User h2) {
   if (h1.getName().equals(h2.getName())) {
       return Integer.compare(h1.getAge(), h2.getAge());
   }
   return h1.getName().compareTo(h2.getName());
}

而后就能够在humans.sort使用这个引用it

@Test
public void testSort_with_givenMethodDefinition() throws Exception {
   ArrayList<User> users = Lists.newArrayList(
          new User("shequ", 22),
          new User("leyuan", 25)
   );
   users.sort(User::compareByNameThenAge);
   Assert.assertThat("shequ", is(equalTo(users.get(1).getName())));
}

使用单独的Comparator

JAVA8已经提供了不少方便的比较器供咱们使用,好比Comparator.comparing方法,因此能够使用Comparator.comparing方法来实现根据User的name进行比较的操做:io

@Test
public void testSort_with_givenInstanceMethod() throws Exception {
   ArrayList<User> users = Lists.newArrayList(
          new User("shequ", 22),
          new User("leyuan", 25)
   );
   Collections.sort(users, Comparator.comparing(User::getName));
   Assert.assertThat("shequ", equalTo(users.get(1).getName()));
}

反序

JDK8中也提供了一个支持倒序排序的方法方便咱们更快的进行倒序

@Test
public void testSort_with_comparatorReverse() throws Exception {
   ArrayList<User> users = Lists.newArrayList(
          new User("shequ", 22),
          new User("leyuan", 25)
   );
   Comparator<User> comparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
   users.sort(comparator.reversed());
   Assert.assertThat("shequ", equalTo(users.get(0).getName()));
}

使用多个条件进行排序

Lambda提供了更复杂的表达式,还能够先对name排序再根据age进行排序:

@Test
public void testSort_with_multipleComparator() throws Exception {
   ArrayList<User> users = Lists.newArrayList(
          new User("shequ", 22),
          new User("leyuan", 25)
   );
   Comparator<User> comparator = (h1, h2) -> {
       if (h1.getName().equals(h2.getName())) {
           return Integer.compare(h1.getAge(), h2.getAge());
       }
       return h1.getName().compareTo(h2.getName());
   };
   users.sort(comparator.reversed());
   Assert.assertThat("shequ", equalTo(users.get(0).getName()));
}

使用多个条件进行排序-组合的方式

Comparator对这种组合的排序有更优雅实现,从JDK8开始,咱们能够使用链式操做进行复合操做来构建更复杂的逻辑:

@Test
public void testSort_with_multipleComparator_composition() throws Exception {
   ArrayList<User> users = Lists.newArrayList(
          new User("leyuan", 22),
          new User("leyuan", 25)
   );   users.sort(Comparator.comparing(User::getName).thenComparing(User::getAge));
   Assert.assertThat(users.get(0), equalTo(new User("leyuan", 22)));
}