สำหรับการเขียนโปรแกรมเชิงฟังก์ชันใน Java เวอร์ชัน Java 9 มาพร้อมกับ IntUnaryOperator ใน Java เรามาดูตัวอย่างกัน −
ตัวอย่าง
import java.util.function.IntUnaryOperator;
public class Demo{
public static void main(String args[]){
IntUnaryOperator op_1 = IntUnaryOperator.identity();
System.out.println("The identity function :");
System.out.println(op_1.applyAsInt(56));
IntUnaryOperator op_2 = a -> 3 * a;
System.out.println("The applyAsInt function :");
System.out.println(op_2.applyAsInt(56));
IntUnaryOperator op_3 = a -> 3 * a;
System.out.println("The andThen function :");
op_3 = op_3.andThen(a -> 5 * a);
System.out.println(op_3.applyAsInt(56));
IntUnaryOperator op_4 = a -> a / 6;
System.out.println("The compose function :");
op_4 = op_4.compose(a -> a * 9);
System.out.println(op_4.applyAsInt(56));
}
} ผลลัพธ์
The identity function : 56 The applyAsInt function : 168 The andThen function : 840 The compose function : 84
คลาสชื่อ 'Demo' มีฟังก์ชันหลัก ที่นี่ ฟังก์ชัน 'identity' ถูกใช้กับอินสแตนซ์ของ 'IntUnaryOperator' ในทำนองเดียวกัน ฟังก์ชันอื่นๆ เช่น 'applyAsInt', 'andthen' และ 'compose' จะใช้กับอินสแตนซ์ที่สร้างขึ้นใหม่ของ 'IntUnaryOperator' เอาต์พุตของการเรียกใช้ฟังก์ชันทุกครั้งจะถูกพิมพ์บนคอนโซลตามลำดับ