Functional Programming With Java 简明教程

Functional Programming - High Order Functions

如果函数满足以下条件之一,则该函数被视为高阶函数。

  1. 它将一个或多个参数作为函数使用。

  2. 它在执行后返回一个函数。

Java 8 Collections.sort() 方法是高阶函数的理想示例。它将比较方法作为参数接受。请参见以下示例:

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]