`
kanpiaoxue
  • 浏览: 1777068 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Java 8 Comparator: How to Sort a List

 
阅读更多

 

文章地址: https://dzone.com/articles/java-8-comparator-how-to-sort-a-list

 

 

In this article, we’re going to see several examples on how to sort a List in Java 8.

Sort a List of Strings Alphabetically

 
 
 
 
1
List<String> cities = Arrays.asList(
2
       "Milan",
3
       "london",
4
       "San Francisco",
5
       "Tokyo",
6
       "New Delhi"
7
);
8
System.out.println(cities);
9
//[Milan, london, San Francisco, Tokyo, New Delhi]
10
11
cities.sort(String.CASE_INSENSITIVE_ORDER);
12
System.out.println(cities);
13
//[london, Milan, New Delhi, San Francisco, Tokyo]
14
15
cities.sort(Comparator.naturalOrder());
16
System.out.println(cities);
17
//[Milan, New Delhi, San Francisco, Tokyo, london]
 
 

We’ve written London with a lowercase "L" to better highlight differences between Comparator.naturalOrder(), which returns a Comparator that sorts by placing capital letters first, and String.CASE_INSENSITIVE_ORDER, which returns a case-insensitive Comparator.

Basically, in Java 7, we were using Collections.sort() that was accepting a List and, eventually, a Comparator –  in Java 8 we have the new List.sort(), which accepts a Comparator.

Sort a List of Integers

 
 
 
 
1
List<Integer> numbers = Arrays.asList(6, 2, 1, 4, 9);
2
System.out.println(numbers); //[6, 2, 1, 4, 9]
3
4
numbers.sort(Comparator.naturalOrder());
5
System.out.println(numbers); //[1, 2, 4, 6, 9]
 
 

Sort a List by String Field

Let’s suppose we have our Movie class and we want to sort our List by title. We can use Comparator.comparing() and pass a function that extracts the field to use for sorting – title, in this example.

 
 
 
 
1
List<Movie> movies = Arrays.asList(
2
        new Movie("Lord of the rings"),
3
        new Movie("Back to the future"),
4
        new Movie("Carlito's way"),
5
        new Movie("Pulp fiction"));
6
7
movies.sort(Comparator.comparing(Movie::getTitle));
8
9
movies.forEach(System.out::println);
 
 

The output will be:

 
 
 
 
1
Movie{title='Back to the future'}
2
Movie{title='Carlito's way'}
3
Movie{title='Lord of the rings'}
4
Movie{title='Pulp fiction'}
 
 

As you’ve probably noticed, we haven’t passed a Comparator, but the List is correctly sorted. That’s because title, the extracted field, is a String, and a String implements a Comparable interface. If you peek at the Comparator.comparing() implementation, you will see that it calls compareTo on the extracted key.

 
 
 
 
1
return (Comparator<T> & Serializable)
2
            (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));  
 
 

Sort a List by Double Field

In a similar way, we can use Comparator.comparingDouble() for comparing double value. In the example, we want to order our List of movies by rating, from the highest to the lowest.

 
 
 
 
1
List<Movie> movies = Arrays.asList(
2
        new Movie("Lord of the rings", 8.8),
3
        new Movie("Back to the future", 8.5),
4
        new Movie("Carlito's way", 7.9),
5
        new Movie("Pulp fiction", 8.9));
6
7
movies.sort(Comparator.comparingDouble(Movie::getRating)
8
                      .reversed());
9
10
movies.forEach(System.out::println);
 
 

We used the reversed function on the Comparator in order to invert default natural order; that is, from lowest to highest. Comparator.comparingDouble() uses Double.compare() under the hood.

If you need to compare int or long, you can use comparingInt() and comparingLong() respectively.

Sort a List With a Custom Comparator

In the previous examples, we haven’t specified any Comparator since it wasn’t necessary, but let’s see an example in which we define our own Comparator. Our Movie class has a new field – “starred” – set using the third constructor parameter. In the example, we want to sort the list so that we have starred movies at the top of the List. 

 
 
 
 
1
List<Movie> movies = Arrays.asList(
2
        new Movie("Lord of the rings", 8.8, true),
3
        new Movie("Back to the future", 8.5, false),
4
        new Movie("Carlito's way", 7.9, true),
5
        new Movie("Pulp fiction", 8.9, false));
6
7
movies.sort(new Comparator<Movie>() {
8
    @Override
9
    public int compare(Movie m1, Movie m2) {
10
        if(m1.getStarred() == m2.getStarred()){
11
            return 0;
12
        }
13
        return m1.getStarred() ? -1 : 1;
14
     }
15
});
16
17
movies.forEach(System.out::println);
 
 

The result will be:

 
 
 
 
1
Movie{starred=true, title='Lord of the rings', rating=8.8}
2
Movie{starred=true, title='Carlito's way', rating=7.9}
3
Movie{starred=false, title='Back to the future', rating=8.5}
4
Movie{starred=false, title='Pulp fiction', rating=8.9}
 
 

We can, of course, use a lambda expression instead of Anonymous class, as follows:

 
 
 
 
1
movies.sort((m1, m2) -> {
2
    if(m1.getStarred() == m2.getStarred()){
3
        return 0;
4
    }
5
    return m1.getStarred() ? -1 : 1;
6
});
 
 

We can also use Comparator.comparing() again:

 
 
 
 
1
movies.sort(Comparator.comparing(Movie::getStarred, (star1, star2) -> {
2
    if(star1 == star2){
3
         return 0;
4
    }
5
    return star1 ? -1 : 1;
6
}));
 
 

In the last example, Comparator.comparing() takes the function to extract the key to use for sorting as the first parameter, and a Comparator as the second parameter. This Comparator uses the extracted keys for comparison; star1 and star2 are boolean and represent m1.getStarred() and m2.getStarred() respectively.

Sort a List With Chain of Comparators

In the last example, we want to have starred movie at the top and then sort by rating.

 
 
 
 
1
List<Movie> movies = Arrays.asList(
2
        new Movie("Lord of the rings", 8.8, true),
3
        new Movie("Back to the future", 8.5, false),
4
        new Movie("Carlito's way", 7.9, true),
5
        new Movie("Pulp fiction", 8.9, false));
6
7
movies.sort(Comparator.comparing(Movie::getStarred)
8
                      .reversed()
9
                      .thenComparing(Comparator.comparing(Movie::getRating)
10
                      .reversed())
11
);
12
13
movies.forEach(System.out::println);
 
 

And the output is:

 
 
 
 
1
Movie{starred=true, title='Lord of the rings', rating=8.8}
2
Movie{starred=true, title='Carlito's way', rating=7.9}
3
Movie{starred=false, title='Pulp fiction', rating=8.9}
4
Movie{starred=false, title='Back to the future', rating=8.5}
 
 

As you’ve seen, we first sort by starred and then by rating – both reversed because we want highest value and true first.

分享到:
评论

相关推荐

    Java8 Comparator: 列表排序的深入讲解

    Java 8 Comparator 详解 - 列表排序深入讲解 Java 8 中的 Comparator 是一种功能强大的排序工具,通过它可以对列表进行排序。本文将详细介绍如何使用 Java 8 中的 Comparator 对列表进行排序,并提供了多个示例代码...

    java排序Comparator和Comparable

    list.sort(Comparator.comparing(MyObject::getField1).thenComparing(MyObject::getField2)); ``` 在实际开发中,`Comparable`常用于定义类的自然排序逻辑,而`Comparator`则更多地用于定制排序或者在多线程环境中...

    java Comparator 用法 例子

    userList.sort(Comparator.comparing(User::getAge)); ``` Comparator也可以用于TreeMap和TreeSet,它们会根据提供的Comparator进行自动排序: ```java TreeSet&lt;User&gt; treeSet = new TreeSet(Comparator.comparing...

    java List 排序 Collections.sort

    总结起来,`Collections.sort()`是Java中对List进行排序的标准工具,它支持自然排序和自定义排序。了解其工作原理和优化技巧,可以帮助我们在编程实践中更高效地处理数据。通过阅读和理解`Collections.sort()`的源码...

    java8语法详解_Java8_java_java8语法::_源码

    Java 8是Java编程语言的一个重要版本,引入了许多新的特性和功能,极大地提升了开发效率和代码的可读性。在本篇文章中,我们将深入探讨Java 8中的关键语法改进,包括函数式编程、Lambda表达式、Stream API、日期与...

    java的Comparator和Comparable.docx

    在 Java 中,Comparator 和 Comparable 是两个非常重要的接口,它们用于对象的排序操作。这两个接口都是在 java.util 包中定义的,主要用于定制排序规则。 **一、Comparator 接口** Comparator 接口允许我们创建...

    Comparator:比较器Java

    - Java的Collections.sort()方法和Arrays.sort()方法都接受Comparator作为参数,可以用于对List或数组进行排序。 6. **泛型支持**: - Comparator接口是泛型化的,可以适用于任何类型。例如,Comparator可以用于...

    java使用stream对日期排序

    在Java编程中,Stream API是Java 8引入的一个强大特性,它允许我们以声明性方式处理数据集合。本文将深入探讨如何使用Stream API对日期进行排序。日期排序在数据分析、日志处理、报表生成等场景中非常常见。下面我们...

    Java8 Comparator排序方法实例详解

    Java8 Comparator排序方法实例详解 Java8 Comparator排序方法实例详解是Java8中的一种排序方法,它提供了一些静态方法,方便我们进行排序操作。Comparator是一个函数式接口,提供了compare、equals、naturalOrder、...

    List对象集合的排序:比较器Comparator(简单例子)

    在`List`对象集合中使用`Comparator`进行排序,通常需要调用`Collections.sort()`或`list.sort()`方法。例如,假设我们有一个`Person`类,其中包含`name`和`age`属性,我们想要根据年龄对`Person`对象列表进行排序:...

    Java对List多个排序、查询条件的处理

    在Java的`java.util`包中,`Collections.sort()`方法提供了对List进行单维度排序的功能。默认情况下,它是基于元素自然顺序进行排序,但如果需要自定义排序规则,可以提供一个`Comparator`实例。例如: ```java ...

    详解JAVA使用Comparator接口实现自定义排序

    在使用Comparator接口时,我们可以使用Collections.sort方法或List接口的sort方法来对对象进行排序。例如,在上面的示例代码中,我们使用了List接口的sort方法来对User对象列表进行排序。 使用Comparator接口可以...

    java中list排序

    在 Java 中,对 List 排序可以使用 Collections.sort(list) 方法,但是这种方法只能对基本类型的 List 进行排序,如果 List 中包含的是对象,那么这种方法就不行了。这时需要使用Comparator接口来实现排序。 ...

    Java用Comparator来排序.pdf

    在Java 8之前,我们通常通过实现Comparator接口并重写`compare()`方法来创建自定义的比较器。例如: ```java inventory.sort(new Comparator() { public int compare(Apple a1, Apple a2){ return a1.getWeight()...

    java 集合分组与排序

    总结来说,Java集合框架提供了强大的工具来处理分组和排序,包括`List`接口的`sort()`方法和流API的`groupingBy()`和`sorted()`。在实际项目中,可以根据需求选择合适的方法。同时,`ArrayHelp`和`ClassLoadUtil`...

    Java+8实战_Java8_java8_

    4. **方法引用来替代lambda**:在某些情况下,可以直接使用方法引用代替lambda表达式,如`Arrays.sort(list, Comparator.comparing(Person::getName))`。 5. **日期和时间API**:Java 8用全新的`java.time`包取代了...

    Java中的Comparator 对多个排序条件的处理

    一种常见的做法是使用`thenComparing()`方法,这是Java 8引入的`Comparator`链式调用的一部分。以下是如何使用`thenComparing()`来实现先按姓氏,后按名字排序的例子: ```java Comparator&lt;Person&gt; multiComparator...

    暑期培训学习笔记之 java\日期排序

    - **List排序**:如果你有一个包含`Date`对象的`List`,可以使用`Collections.sort()`方法,配合自定义的`Comparator`。对于Java 8及以上版本,可以使用`lambda`表达式简化代码: ```java List&lt;Date&gt; dates = ......

    java List中对象多属性排序及各属性排序设置

    首先,我们要理解Java List接口中的sort()方法,它是Java 8引入的,用于对整个List进行原地排序。默认情况下,sort()会根据对象的自然顺序进行排序,但这并不适用于拥有多个属性的对象。因此,我们需要创建自定义的...

    java8stream对list操作常用总结

    list.sort(Comparator.comparing(Mission::getMissId).reversed()); ``` Stream API 的强大之处在于它可以与其他函数式接口,如 `Predicate`、`Function` 和 `Consumer` 结合使用,实现复杂的过滤、映射和消耗...

Global site tag (gtag.js) - Google Analytics