Search code examples
javajava-streamcollectors

modify the list of object one of the property if found more then 1 record in a group in the list using java 8


I have class Employee which have 3 fields.

And I have a list of DTO objects.

`public class Employee {
   private String empId;
   private String name;
   private String group;
   private String salary;
   private String incentive;         
}`

`List<Employee> listEmployees = new ArrayList<>(List.of(
 new Employee("101"."Mark", "A", 20000, 10),
 new Employee("102"."Tom", "B", 3000, 15),
 new Employee("103"."Travis", "C", 5000, 12),
 new Employee("104"."Diana", "D", 3500, 11),
 new Employee("105"."Keith", "B", 4200, 15),
 new Employee("106"."Liam", "D", 6500, 11),
 new Employee("107"."Whitney", "B", 6100, 15),
 new Employee("108"."Tina", "B",2900, 15)
 new Employee("109"."Patrick", "D", 3400, 11)
 ));`

I want to modify the incentive of 5% for all the employees in the same group, if there are more than one employee in a group. For example for above example there is more than one employee in the list of employee group B & D so in this case I want to modify the incentive to 5% for all the employees in the same group. But there is only one employee for group A & C so I don't modify anything for this employee.

For example any company decides to give incentive to employee every year, but if a department has more than a specific number (Example 100) of employees, they want to update the incentive value for all the employees in that same department. But other departments that have a specific number((Example 100)) of employees are less, so the incentive doesn't change.

I tried for example like :

employeeList.stream() .collect(Collectors.groupingBy(Employee::group));

So my result would be like below. (only A and C no need modify because only one record in this group)

`Employee("101"."Mark", "A", 20000, 10)
 Employee("102"."Tom", "B", 3000, 5),
 Employee("103"."Travis", "C", 5000, 12),
 Employee("104"."Diana", "D", 3500, 5),
 Employee("105"."Keith", "B", 4200, 5),
 Employee("106"."Liam", "D", 6500, 5),
 Employee("107"."Whitney", "B", 6100, 5),
 Employee("108"."Tina", "B",2900, 5)
 Employee("109"."Patrick", "D", 3400, 5)`

Solution

  • You can first use Collectors.groupingBy to get the counts, then create a new List based on that.

    Map<String, Long> groupFreq = listEmployees.stream().collect(Collectors.groupingBy(Employee::group, Collectors.counting()));
    List<Employee> result = listEmployees.stream().map(e -> {
        if (groupFreq.get(e.group()) > 1) 
            return new Employee(e.empId(), e.name(), e.group(), e.salary(), 5);
        return e;
    }).collect(Collectors.toList()); // or .toList() in Java 16+