How to do it...

To illustrate the use of method and constructor references, follow these steps:

  1. Create a service implementation named EmployeeDataService, which will provide instances of empty Employee instances and a zero-sized ArrayList object for a list of employees. Also, it has a method that converts an employee's birthday from a long value to a java.util.Date object:
@Service("employeeDataService") 
public class EmployeeDataService { 
   
  public Employee createEmployee(){ 
    Supplier<Employee> newEmp = Employee::new; 
    return newEmp.get(); 
  } 
   
  public List<Employee> startList(){ 
    Supplier<List<Employee>> newList = ArrayList::new; 
    return newList.get(); 
  } 
 
  public Date convertBday(long bdayLong){ 
    Function<Long, Date> bday = Date::new; 
    return bday.apply(bdayLong); 
  } 
}
  1. Then, create another service class, GenericReferences, which shows lambda expressions successfully implemented by just calling on some custom or API instances and static methods. The following first method showcases how to implement, straightforwardly, the functional interfaces through using some built-in static methods of any Java or Spring API:
@Service("genericRef") 
public class GenericReferences { 
   
  public int convertInt(String strVal){ 
    Function<String,Integer> convertToInt =    
       Integer::parseInt; 
    return convertToInt.apply(strVal); 
  } 
} 
  1. Add the second method to GenericReferences that gives the shorthand way of implementing lambdas through calling some methods that throw any exceptions (risky methods):
public Date convertBday(String bdayStr){ 
 
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 
  Function<String,Date> birthday = t -> { 
    Date bdate = null; 
    try { 
         bdate = sdf.parse(t); 
    } catch (ParseException e) { 
    bdate = null; 
    } 
   return bdate; 
  }; 
 return birthday.apply(bdayStr); 
} 

The method convertBday() uses a risky method parse() of SimpleDateFormat to convert the input String to the Date object, given the input mask MM/dd/yyyy. Since parse() needs to be handled by a try-catch block, the only simple form that it can get is the original lambda expression form.

  1. Lastly, add the following method that uses the static method to implement a functional interface in a shorter lambda expression form:
public boolean midYearStarted(Date started){ 
   
  Date midYear = new Date("117,5,30"); 
  Predicate<Date> midDayCheck = midYear::before; 
  return midDayCheck.test(started); 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.94.190