文章地址: 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
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
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.
The output will be:
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.
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.
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.
The result will be:
We can, of course, use a lambda expression instead of Anonymous class, as follows:
We can also use Comparator.comparing() again:
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.
And the output is:
As you’ve seen, we first sort by starred and then by rating – both reversed because we want highest value and true first.
相关推荐
Java 8 Comparator 详解 - 列表排序深入讲解 Java 8 中的 Comparator 是一种功能强大的排序工具,通过它可以对列表进行排序。本文将详细介绍如何使用 Java 8 中的 Comparator 对列表进行排序,并提供了多个示例代码...
list.sort(Comparator.comparing(MyObject::getField1).thenComparing(MyObject::getField2)); ``` 在实际开发中,`Comparable`常用于定义类的自然排序逻辑,而`Comparator`则更多地用于定制排序或者在多线程环境中...
userList.sort(Comparator.comparing(User::getAge)); ``` Comparator也可以用于TreeMap和TreeSet,它们会根据提供的Comparator进行自动排序: ```java TreeSet<User> treeSet = new TreeSet(Comparator.comparing...
总结起来,`Collections.sort()`是Java中对List进行排序的标准工具,它支持自然排序和自定义排序。了解其工作原理和优化技巧,可以帮助我们在编程实践中更高效地处理数据。通过阅读和理解`Collections.sort()`的源码...
Java 8是Java编程语言的一个重要版本,引入了许多新的特性和功能,极大地提升了开发效率和代码的可读性。在本篇文章中,我们将深入探讨Java 8中的关键语法改进,包括函数式编程、Lambda表达式、Stream API、日期与...
在 Java 中,Comparator 和 Comparable 是两个非常重要的接口,它们用于对象的排序操作。这两个接口都是在 java.util 包中定义的,主要用于定制排序规则。 **一、Comparator 接口** Comparator 接口允许我们创建...
- Java的Collections.sort()方法和Arrays.sort()方法都接受Comparator作为参数,可以用于对List或数组进行排序。 6. **泛型支持**: - Comparator接口是泛型化的,可以适用于任何类型。例如,Comparator可以用于...
Java8 Comparator排序方法实例详解 Java8 Comparator排序方法实例详解是Java8中的一种排序方法,它提供了一些静态方法,方便我们进行排序操作。Comparator是一个函数式接口,提供了compare、equals、naturalOrder、...
在`List`对象集合中使用`Comparator`进行排序,通常需要调用`Collections.sort()`或`list.sort()`方法。例如,假设我们有一个`Person`类,其中包含`name`和`age`属性,我们想要根据年龄对`Person`对象列表进行排序:...
在Java编程中,Stream API是Java 8引入的一个强大特性,它允许我们以声明性方式处理数据集合。本文将深入探讨如何使用Stream API对日期进行排序。日期排序在数据分析、日志处理、报表生成等场景中非常常见。下面我们...
在Java的`java.util`包中,`Collections.sort()`方法提供了对List进行单维度排序的功能。默认情况下,它是基于元素自然顺序进行排序,但如果需要自定义排序规则,可以提供一个`Comparator`实例。例如: ```java ...
在使用Comparator接口时,我们可以使用Collections.sort方法或List接口的sort方法来对对象进行排序。例如,在上面的示例代码中,我们使用了List接口的sort方法来对User对象列表进行排序。 使用Comparator接口可以...
在 Java 中,对 List 排序可以使用 Collections.sort(list) 方法,但是这种方法只能对基本类型的 List 进行排序,如果 List 中包含的是对象,那么这种方法就不行了。这时需要使用Comparator接口来实现排序。 ...
在Java 8之前,我们通常通过实现Comparator接口并重写`compare()`方法来创建自定义的比较器。例如: ```java inventory.sort(new Comparator() { public int compare(Apple a1, Apple a2){ return a1.getWeight()...
总结来说,Java集合框架提供了强大的工具来处理分组和排序,包括`List`接口的`sort()`方法和流API的`groupingBy()`和`sorted()`。在实际项目中,可以根据需求选择合适的方法。同时,`ArrayHelp`和`ClassLoadUtil`...
4. **方法引用来替代lambda**:在某些情况下,可以直接使用方法引用代替lambda表达式,如`Arrays.sort(list, Comparator.comparing(Person::getName))`。 5. **日期和时间API**:Java 8用全新的`java.time`包取代了...
一种常见的做法是使用`thenComparing()`方法,这是Java 8引入的`Comparator`链式调用的一部分。以下是如何使用`thenComparing()`来实现先按姓氏,后按名字排序的例子: ```java Comparator<Person> multiComparator...
- **List排序**:如果你有一个包含`Date`对象的`List`,可以使用`Collections.sort()`方法,配合自定义的`Comparator`。对于Java 8及以上版本,可以使用`lambda`表达式简化代码: ```java List<Date> dates = ......
首先,我们要理解Java List接口中的sort()方法,它是Java 8引入的,用于对整个List进行原地排序。默认情况下,sort()会根据对象的自然顺序进行排序,但这并不适用于拥有多个属性的对象。因此,我们需要创建自定义的...
list.sort(Comparator.comparing(Mission::getMissId).reversed()); ``` Stream API 的强大之处在于它可以与其他函数式接口,如 `Predicate`、`Function` 和 `Consumer` 结合使用,实现复杂的过滤、映射和消耗...