I’am making a java program using streams which sort employee based on their salary. Program is given below :-
public class EmployeeMain { public static void main(String[] args) { Employee e1 = new Employee(10000, "Adam"); Employee e2 = new Employee(5000, "Peter"); Employee e3 = new Employee(14000, "Robin"); List<Employee> list = Arrays.asList(e1, e2, e3); Collections.sort(list, (emp1, emp2) -> e1.getSalary() > e2.getSalary() ? 1 : e2.getSalary() > e1.getSalary() ? -1 : 0); list.stream().forEach(System.out::println); } }
The output for this code is :-
Employee [salary=10000, name=Adam] Employee [salary=5000, name=Peter] Employee [salary=14000, name=Robin]
What’s the issue with this code?
Advertisement
Answer
You’ve made a typo in the body of the sort method.
Instead of using emp1
and emp2
you used e1
and e2
which are the instances of the employees you instantiated above.
So basically what you wrote gets evaluated to :
Collections.sort(list, (emp1, emp2) -> 10000 > 5000 ? 1 : 5000 > 10000 ? -1 : 0)
Which is
Collections.sort(list, (emp1, emp2) -> 1)
What you want to write is
Collections.sort(list, (emp1, emp2) -> emp1.getSalary() > emp2.getSalary() ? 1 : emp2.getSalary() > emp1.getSalary() ? -1 : 0);
or shorter/better, as stated in the comments
list.sort(Comparator.comparingInt(Employee::getSalary));