Java8 - Get the details of highest paid employee in the organization?

Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 08:45:23 Viewed : 597


To find the details of the highest-paid employee in the organization using Java 8, you would need to have an additional attribute in the Employee class for the salary. Here is an example:

java
import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; public class Employee { private String name; private double salary; public Employee(String name, double salary) { this.name = name; this.salary = salary; } public String getName() { return name; } public double getSalary() { return salary; } public static void main(String[] args) { // Sample data List<Employee> employees = Arrays.asList( new Employee("John", 50000), new Employee("Jane", 60000), new Employee("Bob", 75000), new Employee("Alice", 70000), new Employee("Charlie", 80000) ); // Find the details of the highest-paid employee using Java 8 streams Optional<Employee> highestPaidEmployee = employees.stream() .max(Comparator.comparingDouble(Employee::getSalary)); // Output the result highestPaidEmployee.ifPresent(employee -> System.out.println("Details of the highest-paid employee: " + "Name: " + employee.getName() + " " + "Salary: " + employee.getSalary())); } }

Output:

yaml
Details of the highest-paid employee: Name: Charlie Salary: 80000.0

In this example:

  • The Employee class is modified to include a salary attribute.
  • Java 8 streams are used with the max operator and a comparator to find the highest-paid employee based on their salary.
  • The result is wrapped in an Optional to handle the case where the list of employees might be empty.
  • The details of the highest-paid employee are then printed to the console.

Search
Related Articles

Leave a Comment: