Functional Programming - High Order Functions


Advertisements

A function is considered as a High Order function if it fulfils any one of the following conditions.

  • It takes one or more parameters as functions.

  • It returns a function after its execution.

Java 8 Collections.sort() method is an ideal example of a high order function. It accepts a comparing method as an argument. See the example below −

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class FunctionTester {    
   public static void main(String[] args) {               
      List<Integer> numbers = Arrays.asList(3, 4, 6, 7, 9);

      //Passing a function as lambda expression
      Collections.sort(numbers, (a,b) ->{ return a.compareTo(b); });

      System.out.println(numbers);
      Comparator<Integer> comparator = (a,b) ->{ return a.compareTo(b); };
      Comparator<Integer> reverseComparator = comparator.reversed();
      
      //Passing a function
      Collections.sort(numbers, reverseComparator);
      System.out.println(numbers);
   } 
}

Output

[3, 4, 6, 7, 9]
[9, 7, 6, 4, 3]
Advertisements