You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java Reactor中创建Tuple2、Tuple3等元组?

在Java Reactor中创建Tuple元组的方法

Reactor 专门提供了 reactor.util.function.Tuples 工具类,用来快速创建 Tuple2 到 Tuple8 这些不同长度的元组,这是官方推荐的方式,比直接实例化元组类更简洁。

创建Tuple2

使用 Tuples.of() 方法传入两个参数即可:

import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

public class TupleDemo {
    public static void main(String[] args) {
        Tuple2<String, Integer> userInfo = Tuples.of("Alice", 28);
        // 访问元组元素
        String userName = userInfo.getT1();
        Integer userAge = userInfo.getT2();
    }
}

创建Tuple3及更长元组

Tuples.of() 支持传入2到8个参数,对应创建Tuple2到Tuple8:

// 创建Tuple3
Tuple3<String, Integer, Boolean> activeUser = Tuples.of("Bob", 32, true);

// 创建Tuple4
Tuple4<String, Integer, Boolean, String> fullUser = Tuples.of("Charlie", 25, false, "backend");

直接实例化元组类(不推荐)

虽然可以直接new对应的Tuple类,但官方更建议使用Tuples工具类,因为它的API更统一且可读性更强:

// 不推荐的写法
Tuple2<String, Integer> tuple = new Tuple2<>("Dave", 30);

内容的提问来源于stack exchange,提问作者AlexanderTheGrape

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 00:43:11