Skip to content
TungDaDev's Blog

Java TriFunction tới DecaFunction: functional interface nhiều tham số

Boy playing jenga
Published on
15 mins read

Bạn cần một lambda nhận Entity, Config, Locale rồi trả ra DTO. Gõ TriFunction< vào IDE, và IDE chẳng gợi ý gì. JDK không có interface đó.

Từ Java 8, chúng ta đã quen viết lambda và truyền hàm như một tham số nhờ gói java.util.function. Với các tác vụ đơn lẻ như biến đổi từng phần tử trong Stream, một đầu vào một đầu ra của Function<T, R> là vừa đẹp:

public class FunctionListExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
 
        // Function to convert names to uppercase
        Function<String, String> toUpperCase = str -> str.toUpperCase();
 
        // Apply function to list
        List<String> upperNames = names.stream()
                                       .map(toUpperCase)
                                       .collect(Collectors.toList());
 
        System.out.println("Original names: " + names);
        System.out.println("Uppercase names: " + upperNames);
    }
}

Nhưng hễ cần gom kết quả từ 3 nguồn khác nhau (ghép thông tin từ 3 CompletableFuture, hay cái mapper ở trên) là khựng lại ngay: thư viện chuẩn của JDK chỉ cung cấp tới BiFunction<T, U, R> (2 tham số) là hết cỡ. Lý do là hệ thống kiểu (type system) của Java không có variadic generics (không viết kiểu Function<T..., R> như C++ template hay TypeScript được), nên muốn có hàm bao nhiêu tham số thì phải khai báo bấy nhiêu interface riêng biệt.

Nhân lúc rảnh rỗi, mình viết sẵn trọn bộ functional interface mở rộng từ 3 tham số (TriFunction) lên tới 10 tham số (DecaFunction) để lúc cần có cái copy vào dùng ngay. Có điều đủ bộ không có nghĩa là nên dùng hết, chuyện dừng ở đâu thì để cuối bài.

# BiFunction

Điểm xuất phát có sẵn trong java.util.function là BiFunction<T, U, R>, nhận vào 2 tham số T, U và trả về kết quả kiểu R:

import java.util.function.BiFunction;
 
public class BiFunctionExample {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> sum = (a, b) -> a + b;
        System.out.println("Sum: " + sum.apply(5, 7)); // Output: Sum: 12
    }
}

# TriFunction

Bắt đầu từ 3 tham số trở đi, ta tự định nghĩa @FunctionalInterface theo đúng khuôn mẫu của JDK: một hàm trừu tượng duy nhất apply(...) để hứng lambda/method reference, kèm theo một default method andThen(Function<? super R, S> after) nhận kết quả đầu ra R của hàm hiện tại rồi đẩy tiếp vào một Function một ngôi phía sau để nối chuỗi (pipeline). TriFunction nhận 3 tham số đầu vào T, U, V và trả về R:

/**
 * Represents a function that accepts three arguments and produces a result.
 * This is a three-arity extension to the functional interfaces {@link Function}
 * and {@link java.util.function.BiFunction BiFunction} from the JDK.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <V> the type of the third argument to the function
 * @param <R> the type of the result of the function
 */
@FunctionalInterface
public interface TriFunction<T, U, V, R> {
 
    R apply(T t, U u, V v);
 
    default <S> TriFunction<T, U, V, S> andThen(Function<? super R, S> after) {
        return (t, u, v) -> after.apply(apply(t, u, v));
    }
 
}

Ví dụ:

public class TriFunctionExample {
    public static void main(String[] args) {
        TriFunction<Integer, Integer, Integer, String> sumAndFormat =
            (a, b, c) -> "Sum: " + (a + b + c);
        System.out.println(sumAndFormat.apply(2, 3, 5)); // Output: Sum: 10
    }
}

# QuadFunction

QuadFunction là interface có 4 tham số đầu vào và 1 kết quả đầu ra.

/**
 * Represents a function that accepts four arguments and produces a result.
 * This is a four-arity extension to the functional interfaces {@link Function}
 * and {@link java.util.function.BiFunction BiFunction} from the JDK.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <V> the type of the third argument to the function
 * @param <W> the type of the fourth argument to the function
 * @param <R> the type of the result of the function
 *
 * @see TriFunction
 */
@FunctionalInterface
public interface QuadFunction<T, U, V, W, R> {
 
    R apply(T t, U u, V v, W w);
 
    default <S> QuadFunction<T, U, V, W, S> andThen(Function<? super R, S> after) {
        return (t, u, v, w) -> after.apply(apply(t, u, v, w));
    }
 
}

Ví dụ:

public class QuadFunctionExample {
    public static void main(String[] args) {
        QuadFunction<Integer, Integer, Integer, Integer, Integer> exc =
            (a, b, c, d) -> a * b * c * d;
        System.out.println(exc.apply(1, 2, 3, 4)); // Output: 24
    }
}

# PentaFunction

PentaFunction là interface có 5 tham số đầu vào.

/**
 * Represents a function that accepts five arguments and produces a result.
 * This is a five-arity extension to the functional interfaces {@link Function}
 * and {@link java.util.function.BiFunction BiFunction} from the JDK.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <V> the type of the third argument to the function
 * @param <W> the type of the fourth argument to the function
 * @param <X> the type of the fifth argument to the function
 * @param <R> the type of the result of the function
 *
 * @see QuadFunction
 */
@FunctionalInterface
public interface PentaFunction<T, U, V, W, X, R> {
 
    R apply(T t, U u, V v, W w, X x);
 
    default <S> PentaFunction<T, U, V, W, X, S> andThen(Function<? super R, S> after) {
        return (t, u, v, w, x) -> after.apply(apply(t, u, v, w, x));
    }
 
}

Ví dụ:

public class PentaFunctionExample {
    public static void main(String[] args) {
        PentaFunction<Integer, Integer, Integer, Integer, Integer, Double> average =
            (a, b, c, d, e) -> (a + b + c + d + e) / 5.0;
        System.out.println(average.apply(10, 20, 30, 40, 50)); // Output: 30.0
    }
}

# HexaFunction

HexaFunction là interface có 6 tham số đầu vào.

/**
 * Represents a function that accepts six arguments and produces a result.
 * This is a six-arity extension to the functional interfaces {@link Function}
 * and {@link java.util.function.BiFunction BiFunction} from the JDK.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <V> the type of the third argument to the function
 * @param <W> the type of the fourth argument to the function
 * @param <X> the type of the fifth argument to the function
 * @param <Y> the type of the sixth argument to the function
 * @param <R> the type of the result of the function
 *
 * @see PentaFunction
 */
@FunctionalInterface
public interface HexaFunction<T, U, V, W, X, Y, R> {
 
    R apply(T t, U u, V v, W w, X x, Y y);
 
    default <S> HexaFunction<T, U, V, W, X, Y, S> andThen(Function<? super R, S> after) {
        return (t, u, v, w, x, y) -> after.apply(apply(t, u, v, w, x, y));
    }
 
}

Ví dụ:

public class HexaFunctionExample {
    public static void main(String[] args) {
        HexaFunction<Integer, Integer, Integer, Integer, Integer, Integer, Integer> sum =
            (a, b, c, d, e, f) -> a + b + c + d + e + f;
        System.out.println(sum.apply(1, 2, 3, 4, 5, 6)); // Output: 21
    }
}

# HeptaFunction

HeptaFunction (hay có thể gọi là SeptiFunction) là interface có 7 tham số đầu vào.

/**
 * Represents a function that accepts seven arguments and produces a result.
 * This is a seven-arity extension to the functional interfaces {@link Function}
 * and {@link java.util.function.BiFunction BiFunction} from the JDK.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <V> the type of the third argument to the function
 * @param <W> the type of the fourth argument to the function
 * @param <X> the type of the fifth argument to the function
 * @param <Y> the type of the sixth argument to the function
 * @param <Z> the type of the seventh argument to the function
 * @param <R> the type of the result of the function
 *
 * @see HexaFunction
 */
@FunctionalInterface
public interface HeptaFunction<T, U, V, W, X, Y, Z, R> {
 
    R apply(T t, U u, V v, W w, X x, Y y, Z z);
 
    default <S> HeptaFunction<T, U, V, W, X, Y, Z, S> andThen(Function<? super R, S> after) {
        return (t, u, v, w, x, y, z) -> after.apply(apply(t, u, v, w, x, y, z));
    }
 
}

Ví dụ:

public class HeptaFunctionExample {
    public static void main(String[] args) {
        HeptaFunction<String, String, String, String, String, String, String, String> concat =
            (a, b, c, d, e, f, g) -> String.join("-", a, b, c, d, e, f, g);
        System.out.println(concat.apply("A", "B", "C", "D", "E", "F", "G"));
        // Output: A-B-C-D-E-F-G
    }
}

# OctaFunction

OctaFunction là interface có 8 tham số đầu vào.

/**
 * Represents a function that accepts eight arguments and produces a result.
 * This is an eight-arity extension to the functional interfaces {@link Function}
 * and {@link java.util.function.BiFunction BiFunction} from the JDK.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <V> the type of the third argument to the function
 * @param <W> the type of the fourth argument to the function
 * @param <X> the type of the fifth argument to the function
 * @param <Y> the type of the sixth argument to the function
 * @param <Z> the type of the seventh argument to the function
 * @param <A> the type of the eighth argument to the function
 * @param <R> the type of the result of the function
 *
 * @see HeptaFunction
 */
@FunctionalInterface
public interface OctaFunction<T, U, V, W, X, Y, Z, A, R> {
 
    R apply(T t, U u, V v, W w, X x, Y y, Z z, A a);
 
    default <S> OctaFunction<T, U, V, W, X, Y, Z, A, S> andThen(Function<? super R, S> after) {
        return (t, u, v, w, x, y, z, a) -> after.apply(apply(t, u, v, w, x, y, z, a));
    }
 
}

Ví dụ:

public class OctaFunctionExample {
    public static void main(String[] args) {
        OctaFunction<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> sum =
            (a, b, c, d, e, f, g, h) -> a + b + c + d + e + f + g + h;
        System.out.println(sum.apply(1, 2, 3, 4, 5, 6, 7, 8)); // Output: 36
    }
}

# NonaFunction

NonaFunction là interface có 9 tham số đầu vào.

/**
 * Represents a function that accepts nine arguments and produces a result.
 * This is a nine-arity extension to the functional interfaces {@link Function}
 * and {@link java.util.function.BiFunction BiFunction} from the JDK.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <V> the type of the third argument to the function
 * @param <W> the type of the fourth argument to the function
 * @param <X> the type of the fifth argument to the function
 * @param <Y> the type of the sixth argument to the function
 * @param <Z> the type of the seventh argument to the function
 * @param <A> the type of the eighth argument to the function
 * @param <B> the type of the ninth argument to the function
 * @param <R> the type of the result of the function
 *
 * @see OctaFunction
 */
@FunctionalInterface
public interface NonaFunction<T, U, V, W, X, Y, Z, A, B, R> {
 
    R apply(T t, U u, V v, W w, X x, Y y, Z z, A a, B b);
 
    default <S> NonaFunction<T, U, V, W, X, Y, Z, A, B, S> andThen(Function<? super R, S> after) {
        return (t, u, v, w, x, y, z, a, b) -> after.apply(apply(t, u, v, w, x, y, z, a, b));
    }
 
}

Ví dụ:

public class NonaFunctionExample {
    public static void main(String[] args) {
        NonaFunction<String, String, String, String, String, String, String, String, String, Integer> countLength =
            (a, b, c, d, e, f, g, h, i) -> a.length() + b.length() + c.length() + d.length() + e.length()
                                          + f.length() + g.length() + h.length() + i.length();
        System.out.println(countLength.apply("A", "BB", "CCC", "DDDD", "EEEEE", "F", "GG", "HHH", "IIII"));
        // Output: 25
    }
}

# DecaFunction

DecaFunction là interface có 10 tham số đầu vào.

/**
 * Represents a function that accepts ten arguments and produces a result.
 * This is a ten-arity extension to the functional interfaces {@link Function}
 * and {@link java.util.function.BiFunction BiFunction} from the JDK.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <V> the type of the third argument to the function
 * @param <W> the type of the fourth argument to the function
 * @param <X> the type of the fifth argument to the function
 * @param <Y> the type of the sixth argument to the function
 * @param <Z> the type of the seventh argument to the function
 * @param <A> the type of the eighth argument to the function
 * @param <B> the type of the ninth argument to the function
 * @param <C> the type of the tenth argument to the function
 * @param <R> the type of the result of the function
 *
 * @see NonaFunction
 */
@FunctionalInterface
public interface DecaFunction<T, U, V, W, X, Y, Z, A, B, C, R> {
 
    R apply(T t, U u, V v, W w, X x, Y y, Z z, A a, B b, C c);
 
    default <S> DecaFunction<T, U, V, W, X, Y, Z, A, B, C, S> andThen(Function<? super R, S> after) {
        return (t, u, v, w, x, y, z, a, b, c) -> after.apply(apply(t, u, v, w, x, y, z, a, b, c));
    }
 
}

Ví dụ:

public class DecaFunctionExample {
    public static void main(String[] args) {
        DecaFunction<Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer> exc =
            (a, b, c, d, e, f, g, h, i, j) -> a * b * c * d * e * f * g * h * i * j;
        System.out.println(exc.apply(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); // Output: 3628800
    }
}

Mở rộng tới n tham số thì làm được, nhưng thực tế chẳng ai làm vậy, vì quá nhiều param lại sinh ra vấn đề khác: gọi apply với 8 tham số cùng kiểu Integer thì truyền nhầm thứ tự compiler cũng không bắt được. Từ khoảng 4 tham số trở lên, gom chúng vào một record (Java 16+) thường dễ đọc hơn, rồi dùng Function<MyParams, R> bình thường.

Nếu cần dùng thật thì cũng không phải tự viết: thư viện Vavr có sẵn Function0 tới Function8 (kèm curried(), memoized()), jOOλ có tới Function16.

Một chi tiết nhỏ về generic variance: Function.andThen trong JDK khai báo tham số là Function<? super R, ? extends V> (áp dụng quy tắc PECS: Producer Extends, Consumer Super). Các interface ở trên viết gọn là Function<? super R, S> vẫn biên dịch và chạy bình thường ở hầu hết trường hợp, chỉ kém linh hoạt hơn một chút nếu hàm after trả về kiểu con của kiểu mong muốn. Ngoài ra, nếu không muốn đẻ thêm interface nhiều tham số, dân lập trình hàm còn dùng kỹ thuật Currying, tức biến hàm 3 tham số thành chuỗi các hàm 1 tham số lồng nhau dạng Function<T, Function<U, Function<V, R>>> (viết lambda là a -> b -> c -> a + b + c), dù cú pháp gọi .apply(a).apply(b).apply(c) trong Java nhìn hơi rườm rà.

Các functional interface khác của Java như Consumer<T> (không trả về kết quả) hay Predicate<T> (trả về boolean) cũng có thể mở rộng lên TriConsumer, TriPredicate theo đúng khuôn này.

# lời kết

Quy tắc mình áp: copy TriFunction (3 tham số), lắm là QuadFunction (4 tham số), vào package util của project là đủ. Chừng đó giữ được mạch nối hàm (method chaining) gọn gàng khi làm việc với Stream, ghép kết quả CompletableFuture, hoặc truyền callback giữa các module.

Từ 5 tham số trở lên, người đọc sau rất dễ hoa mắt trước hàng dài kiểu generic <T, U, V, W, X, Y...>. Lúc đó cứ mạnh dạn đóng gói tham số vào một record cho tường minh, rồi quay về dùng Function<MyRecord, R> bình thường.

Chỉ là những ghi chép cá nhân với hy vọng mang lại chút giá trị. Nếu thấy hữu ích, đừng ngại chia sẻ cho bạn bè & đồng nghiệp nhé!

Happy coding 😎 👍🏻 🚀 🔥.