【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)));
}

相關文章
相關標籤/搜索