拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 Java中的TriFunction接口

Java中的TriFunction接口

白鹭 - 2022-09-24 2265 0 2

一、概述

在本文中,我们将定义一个TriFunction FunctionalInterface,它表示一个接受三个参数并计算结果的函数。稍后,我们还将看到一个使用Vavr 库的内置Function3的示例。

2. 创建我们自己的TriFunction接口

从版本8 开始,Java 定义了BiFunction FunctionalInterface它表示一个接受两个参数并计算其结果的函数。为了允许函数组合,它还提供了一个andThen()方法,该方法将另一个Function应用于BiFunction的结果。

同样,我们将定义我们的TriFunction接口并为其提供andThen()方法:

@FunctionalInterface
 public interface TriFunction<T, U, V, R> {
 R apply(T t, U u, V v);
 default <K> TriFunction<T, U, V, K> andThen(Function<? super R, ? extends K> after) {
 Objects.requireNonNull(after);
 return (T t, U u, V v) -> after.apply(apply(t, u, v));
 }
 }

让我们看看如何使用这个接口。我们将定义一个接受三个Integers的函数,将两个第一个操作数相乘,然后将最后一个操作数相加:

static TriFunction<Integer, Integer, Integer, Integer> multiplyThenAdd = (x, y, z) -> x * y + z;

请注意,只有当两个第一个操作数的乘积低于Integer最大值时,此方法的结果才会准确。

例如,我们可以使用andThen()方法来定义一个TriFunction

  • 首先,将multiplyThenAdd()应用于参数

  • 然后,将计算Integer欧几里得除法除以10 的商的Function应用于上一步的结果

static TriFunction<Integer, Integer, Integer, Integer> multiplyThenAddThenDivideByTen = multiplyThenAdd.andThen(x -> x / 10);

我们现在可以编写一些快速测试来检查我们的TriFunction的行为是否符合预期:

@Test
 void whenMultiplyThenAdd_ThenReturnsCorrectResult() {
 assertEquals(25, multiplyThenAdd.apply(2, 10, 5));
 }
 @Test
 void whenMultiplyThenAddThenDivideByTen_ThenReturnsCorrectResult() {
 assertEquals(2, multiplyThenAddThenDivideByTen.apply(2, 10, 5));
 }

最后一点,TriFunction的操作数可以有多种类型。例如,我们可以定义一个TriFunction,它将Integer转换为String或根据Boolean条件返回另一个给定的String

static TriFunction<Integer, String, Boolean, String> convertIntegerOrReturnStringDependingOnCondition = (myInt, myStr, myBool) -> {
 if (Boolean.TRUE.equals(myBool)) {
 return myInt != null ? myInt.toString() : "";
 } else {
 return myStr;
 }
 };

3.使用Vavr的Function3

Vavr 库已经定义了一个具有我们想要的行为的Function3接口。首先,让我们将Vavr依赖添加到我们的项目中:

<dependency>
 <groupId>io.vavr</groupId>
 <artifactId>vavr</artifactId>
 <version>0.10.4</version>
 </dependency>

我们现在可以用它重新定义multiplyThenAdd()multiplyThenAddThenDivideByTen()方法:

static Function3<Integer, Integer, Integer, Integer> multiplyThenAdd = (x, y, z) -> x * y + z;
 static Function3<Integer, Integer, Integer, Integer> multiplyThenAddThenDivideByTen = multiplyThenAdd.andThen(x -> x / 10);

如果我们需要定义多达8 个参数的函数,使用Vavr 可能是一个不错的选择。Function4Function5,...Function8确实已经在库中定义了。

4。结论

在本教程中,我们为一个接受3 个参数的函数实现了自己的FunctionalInterface我们还强调了Vavr 库包含此类函数的实现。


标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *