Java中的函數接口,你都用過了嗎
在這篇文章中,我們將通過示例來學習 Java 函數式接口。
一、函數式接口的特點
- 只包含一個抽象方法的接口稱為函數式接口。
- 它可以有任意數量的默認靜態方法,但只能包含一個抽象方法。它還可以聲明對象類的方法。
- 函數接口也稱為單一抽象方法接口或SAM 接口。
- 函數式接口只有在沒有任何抽象方法時才可以擴展另一個接口。
- Java API 具有許多單方法接口,例如 Runnable、Callable、Comparator、ActionListener等。它們可以使用匿名類語法來實現和實例化。
二、接口示例
創建一個自定義的Sayable接口,這是一個使用@FunctionalInterface注解的函數式接口。@FunctionalInterface注解表示該接口是一個函數式接口,并且只包含一個抽象方法。
1.自定義函數接口示例:
@FunctionalInterface
interface Sayable{
void say(String msg); // abstract method
}
讓我們通過main()方法來演示一個自定義的函數式接口。我們使用Lambda表達式來實現函數式接口。
public class FunctionalInterfacesExample {
public static void main(String[] args) {
Sayable sayable = (msg) -> {
System.out.println(msg);
};
sayable.say("Say something ..");
}
}
2.Predefined 函數接口
Java提供了Predefined的函數式接口,通過使用 lambda 和方法引用來處理函數式編程。
Predicate是檢查條件的函數,它接受一個參數并返回boolean結果。
讓我們來看一下Predicate接口的內部實現。
import java.util.function.Predicate;
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
// 默認方法的實現
return (t) -> test(t) && other.test(t);
}
// 其他默認方法和靜態方法...
}
Predicate接口只包含一個抽象方法test(T t)同時它還包含默認方法和靜態方法。
讓我們創建一個示例來演示Predicate函數式接口的用法:
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 使用Predicate接口檢查數字是否為偶數
Predicate<Integer> evenNumberPredicate = number -> number % 2 == 0;
System.out.println("Even numbers:");
printNumbers(numbers, evenNumberPredicate);
// 使用Predicate接口檢查數字是否大于5
Predicate<Integer> greaterThanFivePredicate = number -> number > 5;
System.out.println("Numbers greater than 5:");
printNumbers(numbers, greaterThanFivePredicate);
}
public static void printNumbers(List<Integer> numbers, Predicate<Integer> predicate) {
for (Integer number : numbers) {
if (predicate.test(number)) {
System.out.println(number);
}
}
}
}
3.Function 函數接口
Function函數接口是Java中的一個函數式接口,它定義了一個接收一個參數并返回結果的函數。它的定義如下:
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
Function接口有兩個泛型參數:T表示輸入參數的類型,R表示返回結果的類型。它包含一個抽象方法apply(),接收一個類型為T的參數,并返回一個類型為R的結果。
Function接口常用于將一個值轉換為另一個值,或者對輸入值進行處理和計算。它可以被用于各種場景,如數據轉換、映射、計算和處理等。
以下是一個使用Function函數接口的示例:
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
// 創建一個Function接口來將字符串轉換為大寫
Function<String, String> uppercaseFunction = str -> str.toUpperCase();
// 使用Function接口將字符串轉換為大寫
String result = uppercaseFunction.apply("hello world");
System.out.println(result); // 輸出: HELLO WORLD
// 使用Function接口將字符串轉換為其長度
Function<String, Integer> lengthFunction = str -> str.length();
int length = lengthFunction.apply("hello");
System.out.println(length); // 輸出: 5
}
}
4.Supplier 函數接口
Supplier用于表示一個提供(供應)結果的函數。它通常用于延遲計算或在需要時生成值。通過調用get()方法,我們可以獲取由Supplier實例提供的結果。
以下是Consumer接口的實現
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
由于Supplier接口只有一個抽象方法,因此可以使用lambda表達式快速創建Supplier實例。下面是一個示例:
import java.util.Random;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
// 創建一個Supplier接口來生成隨機整數
Supplier<Integer> randomIntegerSupplier = () -> new Random().nextInt();
// 使用Supplier接口生成隨機整數
int randomNumber = randomIntegerSupplier.get();
System.out.println(randomNumber);
// 創建一個Supplier接口來生成當前時間戳
Supplier<Long> timestampSupplier = () -> System.currentTimeMillis();
// 使用Supplier接口生成當前時間戳
long timestamp = timestampSupplier.get();
System.out.println(timestamp);
}
}
5.Consumer 函數接口
Consumer用于表示接受一個參數并執行某些操作的函數。它定義了一個名為accept(T t)的抽象方法,接受一個參數,并且沒有返回值。
以下是Consumer接口的簡化版本:
@FunctionalInterface
public interface Consumer<T> {
void accept(T arg0);
}
Consumer接口適用于那些需要對傳入的參數進行某種操作,而不需要返回結果的情況。它可以用于在不同的上下文中執行各種操作,如打印、修改狀態、更新對象等。下面是一個使用Consumer接口的示例:
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
// 使用Consumer接口打印每個名字
Consumer<String> printName = name -> System.out.println(name);
names.forEach(printName);
// 使用Consumer接口修改每個名字為大寫形式
Consumer<String> uppercaseName = name -> {
String uppercase = name.toUpperCase();
System.out.println(uppercase);
};
names.forEach(uppercaseName);
}
}
在上述示例中,我們創建了兩個Consumer接口的實例。第一個printName用于打印每個名字,第二個uppercaseName用于將每個名字轉換為大寫形式并打印。
通過調用forEach()方法并傳入相應的Consumer接口實例,我們可以對列表中的每個元素執行相應的操作。在示例中,我們對名字列表中的每個名字進行了打印和轉換操作。
Consumer接口的使用場景包括遍歷集合、處理回調函數、更新對象狀態等。它提供了一種簡潔的方式來執行針對輸入參數的操作,使得代碼更加清晰和模塊化。
6.BiFunction 函數接口
BiFunction函數式接口表示接受兩個參數并返回結果的函數。它定義了一個名為apply(T t, U u)的抽象方法,接受兩個參數,并返回一個結果。
讓我們來看一下BiFunction接口的簡化版本。
@FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T arg0, U arg1);
}
BiFunction接口適用于那些需要接受兩個輸入參數并產生結果的情況。它可以用于執行各種操作,如計算、轉換、篩選等。下面是一個使用BiFunction接口的示例:
import java.util.function.BiFunction;
public class Main {
public static void main(String[] args) {
// 使用BiFunction接口計算兩個數的和
BiFunction<Integer, Integer, Integer> sumFunction = (a, b) -> a + b;
int sum = sumFunction.apply(5, 3);
System.out.println(sum); // 輸出: 8
// 使用BiFunction接口將兩個字符串拼接起來
BiFunction<String, String, String> concatenateFunction = (str1, str2) -> str1 + str2;
String result = concatenateFunction.apply("Hello, ", "World!");
System.out.println(result); // 輸出: Hello, World!
}
}
7.BiConsumer函數接口
BiConsumer接口,用于表示接受兩個參數并執行某些操作的函數。它定義了一個名為accept(T t, U u)的抽象方法,接受兩個參數,并且沒有返回值。
以下是BiConsumer接口的簡化版本:
import java.util.function.BiConsumer;
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
}
BiConsumer接口適用于那些需要對傳入的兩個參數進行某種操作,而不需要返回結果的情況。它可以用于在不同的上下文中執行各種操作,如打印、修改狀態、更新對象等。下面是一個使用BiConsumer接口的示例:
import java.util.function.BiConsumer;
public class Main {
public static void main(String[] args) {
// 使用BiConsumer接口打印兩個數的和
BiConsumer<Integer, Integer> sumPrinter = (a, b) -> System.out.println(a + b);
sumPrinter.accept(5, 3);
// 使用BiConsumer接口打印兩個字符串的拼接結果
BiConsumer<String, String> concatenationPrinter = (str1, str2) -> System.out.println(str1 + str2);
concatenationPrinter.accept("Hello, ", "World!");
}
}
8.BiPredicate 函數接口
BiPredicate接口用于表示接受兩個參數并返回一個布爾值的函數。它定義了一個名為test(T t, U u)的抽象方法,接受兩個參數,并返回一個布爾值。
以下是BiPredicate接口的簡化版本:
@FunctionalInterface
public interface BiPredicate<T, U> {
boolean test(T t, U u);
// Default methods are defined also
}
BiPredicate接口適用于那些需要對傳入的兩個參數進行某種條件判斷,并返回布爾值的情況。它可以用于執行各種條件判斷,如相等性比較、大小比較、復雜條件判斷等。
下面是一個使用BiPredicate接口的示例:
import java.util.function.BiPredicate;
public class Main {
public static void main(String[] args) {
// 使用BiPredicate接口判斷兩個數是否相等
BiPredicate<Integer, Integer> equalityPredicate = (a, b) -> a.equals(b);
boolean isEqual = equalityPredicate.test(5, 5);
System.out.println(isEqual); // 輸出: true
// 使用BiPredicate接口判斷一個字符串是否包含另一個字符串
BiPredicate<String, String> containsPredicate = (str1, str2) -> str1.contains(str2);
boolean isContains = containsPredicate.test("Hello, World!", "World");
System.out.println(isContains); // 輸出: true
}
}