Skip to content
Advertisement

Java functional programming: create list of object from a different list

I’d like to convert to funcional programming the following method:

public static List<PayrollEntry> payroll(List<Employee> employees) {
    List<PayrollEntry> payrollEntries = new ArrayList<PayrollEntry>();
    for(Employee emp:employees){

        PayrollEntry pEntry = new PayrollEntry(emp,emp.getSalary(),new BigDecimal(1000));
        payrollEntries.add(pEntry);
    }
    return payrollEntries;
}

Someone could show me how can I create an instance of an object based on the current list using functional programming?

Thank you

Advertisement

Answer

You should just use map and collect methods of the stream:

public static List<PayrollEntry> payroll(List<Employee> employees) {
    return employees.stream()
                    .map(emp -> new PayrollEntry(emp,emp.getSalary(),new BigDecimal(1000)))
                    .collect(Collectors.toList());
}

Though it would be better to provide better copy constructor in PayrollEntry:

public class PayrollEntry {
// ...
    public PayrollEntry(Employee emp) {
        this(emp, emp.getSalary(), new BigDecimal(1000));
   }
// ...
}

Then it is possible to use the constructor as a method reference:

public static List<PayrollEntry> payroll(List<Employee> employees) {
    return employees.stream()
                    .filter(Objects::nonNull) // filter out nulls to prevent NPE
                    .map(PayrollEntry::new)
                    .collect(Collectors.toList());
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement