I’d like to convert to funcional programming the following method:
JavaScript
x
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:
JavaScript
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
:
JavaScript
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:
JavaScript
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());
}