Print name of all employees in sorted order from java 8?

To fetch the name of all employees in sorted order, we are using stream function of java 8.

  • Create Employee class with id, name and salary object.
  • Make a list of employee type object.
  • Now get the Stream data from List using arrayList.stream() method.
  • In filter, we find the employees whose salary is greater than 1000.
  • From map, we find the employee’s name using e->e.getName().
  • In sorted() method, we sort employee name in ascending order.
  • From collect() method, we collect all the names.
  • Print the name of all employees.
public class Employee {
	private Integer id;
	private String name;
	private Integer salary;
	
	public Employee(Integer id, String name, Integer salary) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getSalary() {
		return salary;
	}
	public void setSalary(Integer salary) {
		this.salary = salary;
	}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class EmployeeTest {
	public static void main(String[] args) {
		List<Employee> emp = Arrays.asList(new Employee(1, "anup", 120), new Employee(2, "pankaj", 1300),
				new Employee(3, "vijay", 7230), new Employee(4, "ravi", 678), new Employee(5, "aman", 8230));

		List<String> name = emp.stream().filter(r -> r.getSalary() > 1000).map(e -> e.getName()).sorted()
				.collect(Collectors.toList());
		System.out.println("Employee name with sorted order :- " + name);
	}
}

Output :-
Employee name with sorted order :- [aman, pankaj, vijay]