Many of the API classes in Java 1.8 use functional interfaces to simplify service implementation by applying the principles of functional programming. To illustrate what functional programming is, let us implement the following steps:
- Create another version of the EmployeeRecord interface of the previous recipe that uses the @FunctionalInterface annotation:
@FunctionalInterface public interface EmployeeRecordService { public List<Employee> getEmployees(); }
- Also in org.packt.function.codes.service, create a functional interface that highlights a method with parameters:
@FunctionalInterface public interface ComputeSalaryIncrease { public double increase(double current, double increase); default public double demote(double current, double decrease){ return current - (0.2*decrease); } static public double rateAppraisal(double current){ return current * 0.2; } }
- Open EmployeeServiceImpl and create getEmployees() that implements EmployeeRecordService:
public List<Employee> getEmployees(){ EmployeeRecordService employees = ()->{ return employeeDaoImpl.getEmployees(); }; return employees.getEmployees(); }
- Adding the method updateSalary() under that will implement ComputeSalaryIncrease:
public double updateSalary(double current, double increase){ ComputeSalaryIncrease salaryInc = (currSal, inc)->{ double proRate = currSal + (inc *0.2); return proRate; }; return salaryInc.increase(current, increase); }
- Open TestEmployeeService and add the following test methods:
@Test public void testComputeSalary(){ System.out.println(employeeService.updateSalary(2000, 500)); } @Test public void testShowEmployees(){ Iterator<Employee> iterate = employeeService.getEmployees().iterator(); while(iterate.hasNext()){ Employee temp = iterate.next(); System.out.format("%s ", temp.getFirstName()); } }