函數語言程式設計——高階函式



如果函式滿足下列任何一個條件,則認為它是一個高階函式。

  • 它將一個或多個引數作為函式。

  • 它在其執行之後返回函式。

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);
   } 
}

輸出

[3, 4, 6, 7, 9]
[9, 7, 6, 4, 3]
廣告
© . All rights reserved.