02-实现方法多值返回-pair与truple

在实际的项目开发中,我们经常会遇到返回多个值,通常我们使用Map对象、自定义Class对象等方式封装返回结果。但是这种方式,需要定义大量中间类,影响代码的整体质量。

spring 为我们提供了pair 双值与 triple 三值返回对象。

1、pair

具备两个值的键值对,left、right

复制代码
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

提供两种数据对象

**ImmutablePair:**一个不可变的类,一旦创建,就不能更改其值,表示一个只读的键值对。其内部属性提供final申明。

**MutablePair:**一个可变的类,可以在创建之后更改其值,表示一个可变的键值对。

以下是两种对象使用案例

复制代码
public static void main(String[] args) {
        Pair<Integer, Integer> pair = Pair.of(1, 10); //同ImmutablePair.of(1, 10)
        System.out.println(pair.getLeft()); //1
        System.out.println(pair.getRight()); //10
        //pair.setValue(30); //报错:java.lang.UnsupportedOperationException
 
        pair = MutablePair.of(1, 10);
        ((MutablePair<Integer, Integer>) pair).setLeft(100);
        ((MutablePair<Integer, Integer>) pair).setRight(200);
        System.out.println(pair.getLeft()); //100
        System.out.println(pair.getRight()); //200
        pair.setValue(200); 
    }

2、triple

可以存储三个值,left、middle、right,使用方式与pair 类型。

同时也具备了 ImmutableTriple 与 MutableTriple 两种对象使用。

以下是使用案例

复制代码
import org.apache.commons.lang3.tuple.Triple;
 
public class TripleExample {
    public static void main(String[] args) {
        Triple<String, Integer, Boolean> triple = Triple.of("John", 25, true);
        System.out.println("Name: " + triple.getLeft()); // 输出"Name: John"
        System.out.println("Age: " + triple.getMiddle()); // 输出"Age: 25"
        System.out.println("IsMale: " + triple.getRight()); // 输出"IsMale: true"
        triple.setValue("Bob", 30, false);
        System.out.println("Name: " + triple.getLeft()); // 输出"Name: Bob"
        System.out.println("Age: " + triple.getMiddle()); // 输出"Age: 30"
        System.out.println("IsMale: " + triple.getRight()); // 输出"IsMale: false"
    }
}
相关推荐
NE_STOP1 天前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
spring
JavaGuide2 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
玹外之音2 天前
Spring AI MCP 实战:将你的服务升级为 AI 可调用的智能工具
spring·ai编程
来一斤小鲜肉2 天前
Spring AI入门:第一个AI应用跑起来
spring·ai编程
NE_STOP2 天前
springMVC-常见视图组件与RESTFul编程风格
spring
what丶k3 天前
Spring AI 多模态开发全解析:从入门到企业级落地
后端·spring·ai编程
NE_STOP3 天前
springMVC-获取前端请求的数据与三个作用域
spring
莫寒清3 天前
Spring MVC:@PathVariable 注解详解
java·spring·mvc
-大头.3 天前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(1)
spring
莫寒清3 天前
Apache Tika
java·人工智能·spring·apache·知识图谱