Learn how to increase salary of employees by 10% in Java 8 using Stream API , filter(), map(), and Collectors.toList() with a complete example
Code Explanation (Step-by-Step)
- Employee class is created with name, age, and salary fields.
- Constructor is used to initialize employee details.
- Getter and setter methods are created to access and update employee data.
- Arrays.asList() method is used to create a list of Employee objects.
- stream() method is used to convert the employee list into a stream.
- filter() method is used to select only those employees whose salary is less than 20000.
- map() method is used to increase the selected employee salaries by 10%.
- collect(Collectors.toList()) is used to collect the increased salary values into a new list.
- Finally, the increased salary list is printed on the console.
class Employee {
private String name;
private Integer age;
private Double salary;
public Employee(String name, Integer age, Double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public String toString() {
return "Employee Name: " + this.name + " Age: " + this.age + " Salary: " + this.salary;
}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class EmployeeSalaryTest {
public static void main(String[] args) {
List employeeList = Arrays.asList(
new Employee("Negombo", 35, 7000.00),
new Employee("Brent", 56, 100000.00),
new Employee("Matara", 75, 8000.00),
new Employee("Gerry", 43, 120000.00),
new Employee("Galle", 28, 9000.00)
);
List increasedSalaryList = employeeList.stream()
.filter(emp -> emp.getSalary() < 20000)
.map(emp -> emp.getSalary() * 1.10)
.collect(Collectors.toList());
System.out.println("Increase Employee Salary :- " + increasedSalaryList);
}
}
Output :
Increase Employee Salary :- [7700.0, 8800.0, 9900.0]
FAQ :
What is the correct formula to increase salary by 10% in Java?
To decrease a salary by 10%, you need to subtract 10% from the original salary.
salary * 0.90
Which Java 8 methods are used to increase employee salary?
In this example, Java 8 stream(), filter(), map(), and collect() methods are used. The filter() method checks the salary condition, and the map() method is used to calculate the increased salary.
Is salary * 10 correct for a 10% salary increase?
No, salary * 10 is not correct for a 10% salary increase. It multiplies the salary by 10. To increase salary by 10%, you should use salary * 1.10.