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

 

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

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

Guess it doesn’t suck after all!