สำหรับ functional programming ใน Java เวอร์ชัน 9 มี IntUnaryOperator มาให้ใช้งาน
ตัวอย่าง
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 มี main ใช้ identity() คืนค่าเดิม applyAsInt() ใช้ lambda a -> 3*a andThen() chain function (3*a แล้ว 5*a) compose() compose function (a*9 แล้ว /6) ทดสอบด้วยค่า 56