I needed a TriFunction

Since Java 8 you can do such nice functional things, I love it. But, for some reason it has Functions and BiFunctions, but no TriFunctions! So, it was time to add the TriFunction interface. And yes, I’m very immature 😛

  1. import java.util.Objects;
  2. import java.util.function.Function;
  3.  
  4. @FunctionalInterface
  5. public interface TriFunction<S, U, C, K> {
  6.  
  7.   /**
  8.    * Applies this function to the given arguments
  9.    * @param s the first argument
  10.    * @param u the second arguments
  11.    * @param c the third argument
  12.    * @return K
  13.    */
  14.    K apply(S s, U u, C c);
  15.  
  16.   /**
  17.    * Returns a composed function that first applies this function to its input
  18.    * and then applies the {@code after} function to the result.
  19.    * 
  20.    * If evaluation of either function throws an exception, it is relayed to
  21.    * the caller of the composed function.
  22.    * @param <T>
  23.    * @param after
  24.    * @return 
  25.    */
  26.    default <T> TriFunction<S, U, C, T> andThen(Function<? super K, ? extends T> after) {
  27.        Objects.requireNonNull(after);
  28.        return (S s, U u, C c) -> after.apply(apply(s, u, c));
  29.    }
  30. }

 

Now, you can build functions that take 3 arguments and do something with them to return one result, like:

  1.  TriFunction<Boolean, Boolean, Boolean, Boolean> sucks = (s, u, c) 
  2.      -> Stream.of(s, u, c)
  3.           .allMatch(t -> Boolean.TRUE.equals(t));
  4.  
  5.  boolean f = sucks.apply(true, false, true); // f is false

Guess it doesn’t suck after all!