Home > database >  Create a List of Employee having particular age and increase their salary using Streams in Java 8
Create a List of Employee having particular age and increase their salary using Streams in Java 8

Time:09-06

Below is the Employee class.

public static class Employee {
    private String name;
    private int age;
    private int salary;
    
    // constructor, getters, setters, etc.
}

There is a list of employees.

And I need to get the list of employees whose age greater or equal to 32 years, then make their salary increased by 50% and collect those employees in a new list.

Sample data:

List<Employee> el = new ArrayList<Employee>();

el.add(new Employee("A",30,3000));
el.add(new Employee("B",32,3000));
el.add(new Employee("C",33,5000));

My attempt:

el.stream()
    .filter(i -> i.getAge() >= 32)
    .map(i -> i.getSalary() *3 / 2)
    .collect(Collectors.toList());

But this is returning a list of type integer - List<Integer>. Instead, I want the returned list to be a list of Employee type - List<Employee>.

CodePudding user response:

You cant modify data in stream , eventually you need to create new list and store manipulated data in it .

List<Employee> newList = el.stream()
         .map(f -> new Employee(f.getName(),f.getAge(), f.setSalary((f.getSalary()*3)/2)))
         .collect(Collectors.toList());

CodePudding user response:

It's not a good practice to change the state of elements in the stream.

Instead, you can filter employee having the target age with streams. And then apply salary change using method Iterable.forEach().

List<Employee> employeeOlder32 = el.stream()
    .filter(i -> i.getAge() >= 32)
    .toList(); // for Java 16  or collect(Collectors.toList()) for earlier versions
        
employeeOlder32.forEach(employee -> 
    employee.setSalary(employee.getSalary() * 3 / 2)
);

Sidenote: a common practice is to use BigDecimal for prices, salary etc. (not int or double).

  • Related