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:
javaimport 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:
yamlDetails of the highest-paid employee:
Name: Charlie
Salary: 80000.0
In this example:
Employee
class is modified to include a salary
attribute.max
operator and a comparator to find the highest-paid employee based on their salary.Optional
to handle the case where the list of employees might be empty.