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("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;
}
}