使用Lambda进行排序,无法弄清楚为什么在Java中不起作用。

huangapple go评论80阅读模式
英文:

Using Lambda to sort can't figure out why it's not working Java

问题

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

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.sort(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)); // sorts the 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;
    }
}

Note: The corrected code sorts the original list using the .sort() method. The incorrect output you were getting with the .stream().sorted() approach was because the sorting operation using the stream didn't modify the original list; it only provided a new sorted stream as output.

英文:

I have been trying different ways of sorting and 1 of the methods I tried does not give the output I would expect.

I get the expected output from the Lamda sort that is commented out in the code

employees.sort(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge));
Jack 40
John 29
John 30
Snow 22
Tim 21

but from

employees.stream().sorted(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge));

I get this incorrect output

John 30
John 29
Tim 21
Jack 40
Snow 22

Where have I made the mistake?

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(&quot;John&quot;, 30);
Employee john2 = new Employee(&quot;John&quot;, 29);
Employee tim = new Employee(&quot;Tim&quot;, 21);
Employee jack = new Employee(&quot;Jack&quot;, 40);
Employee snow = new Employee(&quot;Snow&quot;, 22);
List&lt;Employee&gt; employees = new ArrayList&lt;&gt;();
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() + &quot; &quot; + 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;
}
}

答案1

得分: 2

.sorted()不是一个终端操作。事实上,在下面的代码行中没有任何操作,因为流是惰性的。要确认,请添加.peek(System.out::println),你会发现这永远不会被执行。要进行排序,请添加终端操作.collect(Collectors.toList())

employees.stream().sorted(Comparator.comparing(Employee::getName)
                                    .thenComparing(Employee::getAge));

来自文档

流是惰性的;只有在启动终端操作时才会对源数据进行计算,并且只在需要时才会消耗源元素。

英文:

.sorted() is not a terminal operation. In fact, nothing happens in below line of code as Streams are lazy. To confirm, just add .peek(System.out::println) and you'll see that this is never executed. To sort, add terminal operation .collect(Collectors.toList())

employees.stream().sorted(Comparator.comparing(Employee::getName)
.thenComparing(Employee::getAge));

From documentation -

> Streams are lazy; computation on the source data is only performed
> when the terminal operation is initiated, and source elements are
> consumed only as needed.

答案2

得分: 1

工作示例对原始列表进行排序,但使用流(Stream)时会返回一个新的已排序列表。示例 - 您必须像下面这样收集它,employeeList 与其他结果一样被排序。

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

The working example sorts the original list but with stream it returns a new sorted one. Example -You have to collect it like below , and employeeList is sorted as other result.

final List&lt;Employee&gt; employeeList = employees.stream().sorted(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)).collect(Collectors.toList());

答案3

得分: 1

流不会修改现有集合。您必须收集(使用终端操作)流以查看对流所做的更改。

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

Stream doesn't modify existing collection. You have to collect(using terminal operation) it to see changes you made on stream.

List&lt;Employee&gt; sortedEmployees = employees.stream().sorted(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)).collect(Collectors.toList())

huangapple
  • 本文由 发表于 2020年8月21日 01:17:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63510145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定