How to assign a common value for all fields of a Collection?

526 Views Asked by At

I have a POJO class called Employee with empName & Salary. I have a collection of Employee as a object with employee details. Now i want to reset the value of particular field to some common value. In this case i want to assign salary to "0" for all employee items in the list.

List<Employee> empList;

public class Employee{
    private String empName = "";
    private int empSalary = "";
}

Instead of iterating through the list of employee using For/Foreach and assigning the required value for all items in list.

Is there any easy or efficient way to achieve the same using any CollectionUtils (Apache commons or any other).

3

There are 3 best solutions below

2
On

Salary being a class variable will automatically be initialized to its default value which is 0. This happens as soon as the object is created irrespective of the fact that it is in some collection or not.

If you want some other common value you can initialize it appropriately in constructor.

If you want to modify the properties of an object after it has been created and added to a collection, then there is no other way apart from iterating the collection and explicitly setting the values.

7
On

I believe you can do this with Commons Collections (which is what you suggest to use):

CollectionUtils.forAllDo(empList, new Closure() {
    public void execute(Object empObject) {
        Employee emp = (Employee)empObject;
        emp.setEmpSalary(salaryValueToSet);
    }
});
0
On

As of Java 7, there is no neat way for 'bulk'-updates on collections. Hopefully this will get better with Java 8, but for now I suggest looking at libraries like for example guava: http://code.google.com/p/guava-libraries/wiki/FunctionalExplained