158 votes

Java 8 : Où se trouve TriFunction (et kin) dans java.util.function ? Ou quelle est l'alternative ?

Je vois java.util.function.BiFunction, donc je peux le faire :

BiFunction<Integer, Integer, Integer> f = (x, y) -> { return 0; };

Et si ce n'était pas suffisant et que j'avais besoin de TriFunction ? Elle n'existe pas !

TriFunction<Integer, Integer, Integer, Integer> f = (x, y, z) -> { return 0; };

Je suppose que je devrais ajouter que je sais que je peux définir ma propre TriFunction, j'essaie simplement de comprendre la raison pour laquelle elle n'est pas incluse dans la bibliothèque standard.

3voto

Vance Points 31

J'ai trouvé le code source de BiFunction ici :

https://github.com/JetBrains/jdk8u_jdk/blob/master/src/share/classes/java/util/function/BiFunction.java

Je l'ai modifié pour créer TriFunction. Comme BiFunction, elle utilise andThen() et non compose(), donc pour certaines applications qui nécessitent compose(), elle peut ne pas être appropriée. Il devrait être parfait pour les types d'objets normaux. Un bon article sur andThen() et compose() peut être trouvé ici :

http://www.deadcoderising.com/2015-09-07-java-8-functional-composition-using-compose-and-andthen/

import java.util.Objects;
import java.util.function.Function;

/**
 * Represents a function that accepts two arguments and produces a result.
 * This is the three-arity specialization of {@link Function}.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object, Object)}.
 *
 * @param <S> the type of the first argument to the function
 * @param <T> the type of the second argument to the function
 * @param <U> the type of the third argument to the function
 * @param <R> the type of the result of the function
 *
 * @see Function
 * @since 1.8
 */
@FunctionalInterface
public interface TriFunction<S, T, U, R> {

    /**
     * Applies this function to the given arguments.
     *
     * @param s the first function argument
     * @param t the second function argument
     * @param u the third function argument
     * @return the function result
     */
    R apply(S s, T t, U u);

    /**
     * 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 <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     */
    default <V> TriFunction<S, T, U, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (S s, T t, U u) -> after.apply(apply(s, t, u));
    }
}

2voto

Payel Senapati Points 459

Simple Function<T, R> peut être utilisé dans un formulaire imbriqué pour émuler une TriFunction

Voici un exemple simple -

       final Function<Integer, Function<Integer, Function<Integer, Double>>> function = num1 -> {
            System.out.println("Taking first parameter");
            return num2 -> {
                System.out.println("Taking second parameter");
                return num3 -> {
                    System.out.println("Taking third parameter");
                    return (double)(num1 + num2 + num3);
                };
            };
        };

        final Double result = function.apply(2).apply(3).apply(4);

        System.out.println("Result -> " + result);

SORTIE -

Taking first parameter
Taking second parameter
Taking third parameter
Result -> 9.0

Cette logique peut être étendue pour qu'une fonction prenne n'importe quel nombre de paramètres.

1voto

Koushik Roy Points 321

Vous ne pouvez pas toujours vous arrêter à TriFunction. Parfois, vous pouvez avoir besoin de passer un nombre n de paramètres à vos fonctions. L'équipe de support devra alors créer une QuadFunction pour corriger votre code. La solution à long terme serait de créer un objet avec les paramètres supplémentaires, puis d'utiliser la fonction ou la bi-fonction prête à l'emploi.

0voto

OscarRyz Points 82553

El réponse choisie est le plus utile, bien que je trouve l'explication un peu alambiquée.

Pour simplifier, disons que vous voulez une fonction qui ajoute deux chaînes de caractères

La méthode

String add(String s, String t) {
    return s + t;
}

Aurait une fonction comme celle-ci avec le même comportement :

Function<String,Function<String,String>> add = s -> t -> s + t;

Et de l'appeler :

var result = add.apply("hello").apply(" world");

Que cela soit ou non idiomatique avec Java est un autre sujet.

0voto

Vadzim Points 4460

Il y a des Consumer3..Consumer8, Function3..Function8, Predicate3..Predicate8 prêts à l'emploi dans le domaine de la santé. reactor.function paquet de Réacteur Bibliothèque de modules complémentaires fournie avec Spring Framework.

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X