.sorted(Comparator.comparingDouble
时间: 2023-12-12 15:34:49 浏览: 25
`.sorted(Comparator.comparingDouble)`是Java 8中的一种排序方式,用于对Double类型的元素进行排序。它可以按照指定的Double类型的属性进行排序,也可以按照多个属性进行排序。下面是一个例子:
假设有一个Student类,其中包含name和score属性,我们想按照score属性对Student对象进行排序,可以使用以下代码:
```java
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", 80.0));
students.add(new Student("Jerry", 90.0));
students.add(new Student("Mike", 70.0));
students.sort(Comparator.comparingDouble(Student::getScore));
```
这里使用了`Comparator.comparingDouble`方法,它接受一个Function作为参数,用于提取需要排序的属性。在这个例子中,我们使用了`Student::getScore`方法提取了score属性。
如果我们想按照多个属性进行排序,可以使用`thenComparing`方法。例如,如果我们想按照score属性升序排序,如果score相同则按照name属性升序排序,可以使用以下代码:
```java
students.sort(Comparator.comparingDouble(Student::getScore).thenComparing(Student::getName));
```
这里使用了`thenComparing`方法,它接受一个Comparator作为参数,用于在前一个排序条件相同时进行比较。在这个例子中,我们使用了`Student::getName`方法提取了name属性。