使用lambda进行排序无法找出它为什么不能工作

gwbalxhn  于 2021-07-08  发布在  Java
关注(0)|答案(3)|浏览(334)

我一直在尝试不同的排序方法,我尝试的方法中有一种没有给出我所期望的结果。
我从代码中注解掉的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;
    }
}
cnh2zyt3

cnh2zyt31#

工作示例对原始列表进行排序,但使用stream返回一个新的排序列表。示例-您必须像下面那样收集它,employeelist作为其他结果进行排序。

final List<Employee> employeeList = employees.stream().sorted(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)).collect(Collectors.toList());
t2a7ltrp

t2a7ltrp2#

流不修改现有集合。您必须收集(使用终端操作)它才能看到您在流中所做的更改。

List<Employee> sortedEmployees = employees.stream().sorted(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)).collect(Collectors.toList())
pn9klfpd

pn9klfpd3#

.sorted() 不是终端操作。事实上,由于流是懒惰的,所以在下面的代码行中什么也不会发生。要确认,只需添加 .peek(System.out::println) 你会发现这是永远不会被执行的。要排序,请添加终端操作 .collect(Collectors.toList()) ```
employees.stream().sorted(Comparator.comparing(Employee::getName)
.thenComparing(Employee::getAge));

来自文档-
溪流是懒惰的;仅当终端操作启动时才对源数据执行计算,并且仅当需要时才消耗源元素。

相关问题