Higher-order functions are functions that take other functions as arguments or return functions as their results.
- In the below example we Search employee by Location using Predicate.
- If we are not using HOF we need to assign new predicate to variable each and everytime like empFromDelhi
- Instead of doing that we have a HOF getEmpByLocation which takes location as string in arguments and returns function in its return type
public class HigherOrdFns { public static void main(String[] args) { Employee objEmp1 = new Employee(101, "Mugil", 30, "Chennai", "600018", 5, 5000); Employee objEmp2 = new Employee(102, "Mani", 33, "Chennai", "600028", 4, 6000); Employee objEmp3 = new Employee(103, "Madhu", 32, "Chennai", "600054", 6, 10000); Employee objEmp4 = new Employee(104, "Vinu", 29, "Bangalore", "500234", 5, 15000); Employee objEmp5 = new Employee(105, "Srini", 40, "Delhi", "622142", 10, 7000); Employee objEmp6 = new Employee(106, "Dimple", 35, "Delhi", "622142", 5, 8000); List<Employee> arrEmployee = Arrays.asList(objEmp1, objEmp2, objEmp3, objEmp4, objEmp5, objEmp6); Predicate<Employee> empFromDelhi = employee -> employee.getLocation().equals("Delhi"); arrEmployee.stream().filter(empFromDelhi).forEach(System.out::println); arrEmployee.stream().filter(getEmpByLocation("Chennai")).forEach(System.out::println); arrEmployee.stream().filter(getEmpByLocation("Bangalore")).forEach(System.out::println); } //Higher Order function which return function as return type private static Predicate<Employee> getEmpByLocation(String location) { return employee -> employee.getLocation().equals(location); } }