Sorting list of Java objects

In this post we will see how to sort a list of java objects using a property of the object. In this example we will sort the list of employees using their salaries.

Employee:


public class Employee {

	@Override
	public String toString() {
		return "Employee [salary=" + salary + ", department=" + department + ", name=" + name + "]";
	}

	public Employee(int salary, String name, String department) {
		this.salary = salary;
		this.name = name;
		this.department = department;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	int salary;

	String department;

	String name;

}

For sorting create stream of employees and invoke sorted method.

package src;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Sorting {
	
	static List<Employee> employees = new ArrayList<Employee>();
	
	public static List<Employee> sortASC(List<Employee> employees) {
		return employees.stream().sorted((Employee emp1,Employee emp2) -> emp1.getSalary()-emp2.getSalary()).collect(Collectors.toList());
		
	}
	
	public static List<Employee> sortDESC(List<Employee> employees) {
		return employees.stream().sorted((Employee emp1,Employee emp2) -> emp2.getSalary()-emp1.getSalary()).collect(Collectors.toList());
		
	}
	
	public static void main(String args[]) {
		
		Employee emp1 = new Employee(5000,"Mike","Mech");		
		Employee emp2 = new Employee(3000,"Bran","CSE");		
		Employee emp3 = new Employee(6000,"Robert","Electrical");
		
		employees.add(emp1);
		employees.add(emp2);
		employees.add(emp3);
		
		System.out.println("Sort Ascending based on employee Salary....");
		
		sortASC(employees).stream().forEach(System.out::println);
		
		System.out.println("");
		
		System.out.println("Sort Descending based on employee Salary....");
		
		sortDESC(employees).stream().forEach(System.out::println);
		
	}

}

Output:

Sort Ascending based on employee Salary....
Employee [salary=3000, department=CSE, name=Bran]
Employee [salary=5000, department=Mech, name=Mike]
Employee [salary=6000, department=Electrical, name=Robert]

Sort Descending based on employee Salary....
Employee [salary=6000, department=Electrical, name=Robert]
Employee [salary=5000, department=Mech, name=Mike]
Employee [salary=3000, department=CSE, name=Bran]

Leave a Reply

Your email address will not be published. Required fields are marked *