一文帶你掌握J(rèn)ava8中函數(shù)式接口的使用和自定義
函數(shù)式接口是 Java 8 引入的一種接口,用于支持函數(shù)式編程。函數(shù)式接口通常包含一個抽象方法,可以被 Lambda 表達(dá)式或方法引用所實現(xiàn)。在本文中,我們將深入探討函數(shù)式接口的概念、用途以及如何創(chuàng)建和使用函數(shù)式接口。
什么是函數(shù)式接口
函數(shù)式接口是只包含一個抽象方法的接口。但是默認(rèn)方法和靜態(tài)方法在此接口中可以定義多個。Java 中的函數(shù)式接口可以被用作 Lambda 表達(dá)式的目標(biāo)類型。通過函數(shù)式接口,可以實現(xiàn)更簡潔、更具可讀性的代碼,從而支持函數(shù)式編程的思想。
常見函數(shù)式接口
Java 中有一些內(nèi)置的函數(shù)式接口,用于不同的用途:
- Runnable: 用于描述可以在單獨線程中執(zhí)行的任務(wù)。
- Callable: 類似于 Runnable,但可以返回執(zhí)行結(jié)果或拋出異常。
- Comparator: 用于比較兩個對象的順序。
- Function: 接受一個參數(shù)并產(chǎn)生一個結(jié)果。
- Predicate: 接受一個參數(shù)并返回一個布爾值,用于判斷條件是否滿足。
- Supplier: 不接受參數(shù),但返回一個值。
自定義函數(shù)式接口
自定義函數(shù)式接口是需要在接口上添加 @FunctionalInterface
注解
定義 CustomFunctionalInterface 接口函數(shù)
@java.lang.FunctionalInterface public interface CustomFunctionalInterface { void execute(); }
在上述代碼中,定義了一個名為 CustomFunctionalInterface
的函數(shù)式接口,其中包含一個抽象方法 execute
,這是一個無參無返回值的方法。通過使用 @FunctionalInterface
注解,明確告訴編譯器這是一個函數(shù)式接口,確保它只包含一個抽象方法。
基于 CustomFunctionalInterface 使用
public class CustomFunctionInterfaceTest { public void test(CustomFunctionalInterface functionalInterface) { functionalInterface.execute(); } @Test public void execute() { test(() -> System.out.println("Hello World Custom!")); } }
在測試類 CustomFunctionInterfaceTest
中,定義了一個名為 test
的方法,接受一個 CustomFunctionalInterface
參數(shù),并在方法體中調(diào)用了 execute
方法。這個方法允許將任意實現(xiàn)了 CustomFunctionalInterface
的 Lambda 表達(dá)式傳遞進來,并執(zhí)行其 execute
方法。
在測試方法 execute
中,通過調(diào)用 test
方法,傳遞了一個 Lambda 表達(dá)式 () -> System.out.println("Hello World Custom!")
。這個 Lambda 表達(dá)式實現(xiàn)了 CustomFunctionalInterface
的抽象方法 execute
,即打印了一條 "Hello World Custom!" 的消息。
常見函數(shù)式接口基本使用
Predicate
當(dāng)涉及到對集合或數(shù)據(jù)進行篩選時,Java 中的函數(shù)式接口 Predicate
可以發(fā)揮重要作用。Predicate
是一個通用的函數(shù)式接口,用于定義一個接受參數(shù)并返回布爾值的操作,用于判斷條件是否滿足。
Predicate 函數(shù)式接口
@FunctionalInterface public interface Predicate<T> { boolean test(T t); }
基于 Predicate 進行篩選
import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class PredicateExample { public static List<String> filterStrings(List<String> list, Predicate<String> predicate) { List<String> filteredList = new ArrayList<>(); for (String str : list) { if (predicate.test(str)) { filteredList.add(str); } } return filteredList; } public static void main(String[] args) { List<String> stringList = List.of("apple", "banana", "cherry", "date", "elderberry"); Predicate<String> lengthPredicate = str -> str.length() > 5; List<String> longStrings = filterStrings(stringList, lengthPredicate); System.out.println("Long strings: " + longStrings); } }
在這個示例中,我們定義了一個 filterStrings
方法,它接受一個字符串列表和一個 Predicate
參數(shù),并返回符合條件的字符串列表。在 main
方法中,我們創(chuàng)建了一個長度判斷的 Predicate
,然后使用它來篩選出長度大于 5 的字符串。
Consumer
函數(shù)式接口 Consumer
在 Java 中用于表示接受一個參數(shù)并且沒有返回值的操作。它可以用于執(zhí)行一些對輸入數(shù)據(jù)的處理,例如打印、修改等。
Consumer 函數(shù)式接口
@FunctionalInterface public interface Consumer<T> { void accept(T t); }
基于 Consumer 進行篩選
import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class ConsumerExample { public static void processIntegers(List<Integer> list, Consumer<Integer> consumer) { for (Integer num : list) { consumer.accept(num); } } public static void main(String[] args) { List<Integer> integerList = List.of(1, 2, 3, 4, 5); Consumer<Integer> squareAndPrint = num -> { int square = num * num; System.out.println("Square of " + num + " is: " + square); }; processIntegers(integerList, squareAndPrint); } }
在這個示例中,我們定義了一個 filterStrings
方法,它接受一個字符串列表和一個 Predicate
參數(shù),并返回符合條件的字符串列表。在 main
方法中,我們創(chuàng)建了一個長度判斷的 Predicate
,然后使用它來篩選出長度大于 5 的字符串。
在這個示例中,我們定義了一個 processIntegers
方法,它接受一個整數(shù)列表和一個 Consumer
參數(shù),并在方法內(nèi)遍歷列表,對每個元素執(zhí)行 accept
方法。在 main
方法中,我們創(chuàng)建了一個 Consumer
實現(xiàn) squareAndPrint
,它會計算每個元素的平方并打印出來。
Function
函數(shù)式接口 Function
在 Java 中用于表示一個接受一個參數(shù)并產(chǎn)生一個結(jié)果的操作。它可以用于執(zhí)行各種轉(zhuǎn)換、映射和處理操作。
Function 函數(shù)式接口
Function
接口定義了一個名為 apply
的抽象方法,接受一個參數(shù)并返回一個結(jié)果。這個接口用于表示一個對輸入數(shù)據(jù)的轉(zhuǎn)換操作。
@FunctionalInterface public interface Function<T, R> { R apply(T t); }
在上述定義中,T
表示輸入類型,R
表示輸出類型。
基于 Function 進行數(shù)據(jù)轉(zhuǎn)換
轉(zhuǎn)換為大寫
import java.util.function.Function; public class FunctionExample { public static String convertToUpperCase(String input, Function<String, String> function) { return function.apply(input); } public static void main(String[] args) { String original = "hello world"; String upperCase = convertToUpperCase(original, str -> str.toUpperCase()); System.out.println(upperCase); } }
在這個示例中,我們定義了一個 convertToUpperCase
方法,它接受一個字符串和一個 Function
參數(shù),用于將輸入字符串轉(zhuǎn)換為大寫。在 main
方法中,我們通過傳遞一個 Function
實現(xiàn)來執(zhí)行轉(zhuǎn)換操作。
字符串長度映射
import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; public class FunctionExample { public static List<Integer> mapStringLengths(List<String> list, Function<String, Integer> function) { return list.stream() .map(function) .collect(Collectors.toList()); } public static void main(String[] args) { List<String> strings = List.of("apple", "banana", "cherry", "date"); List<Integer> lengths = mapStringLengths(strings, str -> str.length()); System.out.println(lengths); } }
在這個示例中,我們定義了一個 mapStringLengths
方法,它接受一個字符串列表和一個 Function
參數(shù),用于將輸入字符串映射為它們的長度。通過使用 map
操作,我們在列表中的每個字符串上執(zhí)行了長度映射。
Supplier
函數(shù)式接口 Supplier
在 Java 中用于表示一個不接受參數(shù)但產(chǎn)生一個結(jié)果的操作。它通常用于延遲計算,只在需要時才執(zhí)行操作并生成結(jié)果。
Supplier 函數(shù)式接口
Supplier
接口定義了一個名為 get
的抽象方法,用于獲取一個結(jié)果。這個接口用于表示一個無參操作,只產(chǎn)生結(jié)果。
javaCopy code @FunctionalInterface public interface Supplier<T> { T get(); }
在上述定義中,T
表示結(jié)果的類型
基于 Supplier 進行延遲計算
隨機數(shù)生成
import java.util.Random; import java.util.function.Supplier; public class SupplierExample { public static int generateRandomNumber(Supplier<Integer> supplier) { return supplier.get(); } public static void main(String[] args) { Supplier<Integer> randomSupplier = () -> new Random().nextInt(100); int randomNumber = generateRandomNumber(randomSupplier); System.out.println("Random number: " + randomNumber); } }
在這個示例中,我們定義了一個 generateRandomNumber
方法,它接受一個 Supplier
參數(shù),并通過調(diào)用 get
方法獲取隨機數(shù)。在 main
方法中,我們創(chuàng)建了一個隨機數(shù)生成的 Supplier
,然后將它傳遞給 generateRandomNumber
方法來獲取隨機數(shù)。
延遲初始化
import java.util.function.Supplier; public class SupplierExample { private String expensiveResource = null; public String getExpensiveResource(Supplier<String> supplier) { if (expensiveResource == null) { expensiveResource = supplier.get(); } return expensiveResource; } public static void main(String[] args) { Supplier<String> resourceSupplier = () -> { System.out.println("Initializing expensive resource..."); return "Expensive Resource"; }; SupplierExample example = new SupplierExample(); System.out.println(example.getExpensiveResource(resourceSupplier)); System.out.println(example.getExpensiveResource(resourceSupplier)); } }
在這個示例中,我們定義了一個 getExpensiveResource
方法,它接受一個 Supplier
參數(shù),并使用延遲初始化的方式獲取昂貴的資源。在 main
方法中,我們創(chuàng)建了一個資源初始化的 Supplier
,然后多次調(diào)用 getExpensiveResource
方法,觀察只有在需要時才會初始化資源。
到此這篇關(guān)于一文帶你掌握J(rèn)ava8中函數(shù)式接口的使用和自定義的文章就介紹到這了,更多相關(guān)Java8函數(shù)式接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Boot 統(tǒng)一數(shù)據(jù)返回格式的解決方案
統(tǒng)?的數(shù)據(jù)返回格式使? @ControllerAdvice 和 ResponseBodyAdvice 的?式實現(xiàn),下面給大家分享Spring Boot 統(tǒng)一數(shù)據(jù)返回格式的解決方案,感興趣的朋友一起看看吧2024-03-03intellij idea14打包apk文件和查看sha1值
這篇文章主要為大家詳細(xì)介紹了intellij idea14打包apk文件和查看sha1值,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-10-10Java8 Stream API 詳細(xì)使用方法與操作技巧指南
這篇文章主要介紹了Java8 Stream API 詳細(xì)使用方法與操作技巧,總結(jié)分析了Java8 Stream API 基本功能、使用方法與操作注意事項,需要的朋友可以參考下2020-05-05