我一直在尝试不同的排序方法,我尝试的方法中有一种没有给出我所期望的结果。
我从代码中注解掉的lamda排序中得到预期的输出
employees.sort(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge));
Jack 40
John 29
John 30
Snow 22
Tim 21
但是从
employees.stream().sorted(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge));
我得到了不正确的输出
John 30
John 29
Tim 21
Jack 40
Snow 22
我哪里犯的错?
package com;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Employee john = new Employee("John", 30);
Employee john2 = new Employee("John", 29);
Employee tim = new Employee("Tim", 21);
Employee jack = new Employee("Jack", 40);
Employee snow = new Employee("Snow", 22);
List<Employee> employees = new ArrayList<>();
employees.add(john);
employees.add(john2);
employees.add(tim);
employees.add(jack);
employees.add(snow);
employees.stream().sorted(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)); //does not sort original list
//employees.sort(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)); //sorts original list
for(Employee employee : employees){
System.out.println(employee.getName() + " " + employee.getAge());
}
}
}
class Employee{
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
3条答案
按热度按时间cnh2zyt31#
工作示例对原始列表进行排序,但使用stream返回一个新的排序列表。示例-您必须像下面那样收集它,employeelist作为其他结果进行排序。
t2a7ltrp2#
流不修改现有集合。您必须收集(使用终端操作)它才能看到您在流中所做的更改。
pn9klfpd3#
.sorted()
不是终端操作。事实上,由于流是懒惰的,所以在下面的代码行中什么也不会发生。要确认,只需添加.peek(System.out::println)
你会发现这是永远不会被执行的。要排序,请添加终端操作.collect(Collectors.toList())
```employees.stream().sorted(Comparator.comparing(Employee::getName)
.thenComparing(Employee::getAge));