Java 中的 IntFunction 介面及示例
在 Java 中,IntFunction 介面是一個函式式介面,它表示一個接受整型值作為引數並返回任何資料型別結果的函式。這裡的函式式介面指的是隻包含一個抽象方法並體現單一功能的介面。一些函式式介面的例子包括 Predicate、Runnable 和 Comparable 介面。IntFunction 介面定義在 'java.util.function' 包中。在本文中,我們將透過示例程式來探索 IntFunction 介面及其內建方法。
Java 中的 IntFunction 介面
IntFunction 介面只有一個抽象方法,稱為'apply()'。但在討論此方法之前,讓我們先看看 IntFunction 介面的語法。
語法
public interface IntFunction
在程式中使用此介面之前,需要匯入它。要匯入 IntFunction 介面,請使用以下命令:
import java.util.function.IntFunction;
IntFunction 介面的 apply() 方法的使用
’apply()’ 方法是 IntFunction 介面的內建函式方法,它接受單個整型輸入,並將 IntFunction 介面應用於給定的引數。
語法
instance.apply(int val)
這裡,'instance' 指定 IntFunction 的例項,'val' 指定將對其執行操作的運算元。
示例 1
以下示例演示了在列印指定整型變數的平方和立方時如何使用 'apply()' 方法。
方法
首先,匯入前面提到的所需包。
然後,建立兩個 IntFunction 例項。第一個將返回指定整型變數的平方,第二個將返回其立方。
最後,使用 'apply()' 方法以及 IntFunction 的例項,並傳遞所需的整數值來執行這兩個操作。
import java.util.function.IntFunction;
public class IntFunctionExample1 {
public static void main(String[] args) {
// creating instances of IntFunction
IntFunction printSquare = n1 -> n1 * n1;
IntFunction printCube = n2 -> n2 * n2 * n2;
// to print the result
System.out.println("Square of specified value: " + printSquare.apply(5));
System.out.println("Cube of specified value: " + printCube.apply(2));
}
}
輸出
Square of specified value: 25 Cube of specified value: 8
使用流與 IntFunction 介面
在 Java 中,流允許我們對指定元素執行函式式操作。它簡單地將源元素(例如集合框架的類)透過各種內建方法傳遞,以返回結果。
示例 2
在下面的示例中,我們將使用流與 IntFunction 介面將整數集合轉換為字串。
方法
首先,匯入所需的包,以便我們可以使用流和 IntFunction 介面。
建立一個整數列表。
然後,定義一個 IntFunction 介面的例項,它將執行將整數轉換為字串的操作。
現在,使用 IntFunction 介面的例項以及 stream() 和 collect() 將整數轉換為字串。這裡,stream() 指定以流的形式輸入。
import java.util.*;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
public class IntFunctionExample2 {
public static void main(String[] args) {
// creating a list of integers
List<Integer> AList = Arrays.asList(11, 22, 33, 44, 55);
// using IntFunction to convert elements to a String
IntFunction<String> intToString = i -> String.valueOf(i);
// Using the IntFunction to convert the list of integers into a list of strings
List<String> strings = AList.stream()
// convert Integer to int
.mapToInt(i -> i)
// applying the IntFunction
.mapToObj(intToString)
// collecting the result
.collect(Collectors.toList());
// Printing the result
System.out.println("The elements of the list: " + strings);
}
}
輸出
The elements of the list: [11, 22, 33, 44, 55]
結論
在本文中,我們學習了 IntFunction 介面,它是一種函式式介面。使用 IntFunction 介面的優點之一是它允許我們使用 lambda 表示式編寫程式碼。此外,我們可以將它們與 Stream API 或其他接受函式式介面作為引數的方法一起使用。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP