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"
    }
}
相关推荐
剑胆琴心静水深流7 小时前
全栈之路6---web集成与呈现
前端·vue.js·spring boot·分布式·spring·前端框架·npm
晓晓_za89866810 小时前
Geo 优化服务 CI/CD 流水线搭建:源码自动构建、测试与灰度发布
运维·服务器·tcp/ip·spring·缓存·ci/cd
卓怡学长11 小时前
w180springboot基于Java的悠扬乐器管理
java·spring boot·mysql·spring·maven·intellij-idea
小白说大模型13 小时前
Spring AI 框架中集成 MCP 的完整指南:从服务端到客户端的全流程实践
大数据·数据库·人工智能·安全·spring·chatgpt·开源
卓怡学长14 小时前
w181springboot机场乘客服务系统
java·数据库·spring boot·spring·intellij-idea
卓怡学长19 小时前
w192基于springboot教务管理系统
java·数据库·spring boot·spring·maven·intellij-idea
手握风云-19 小时前
Spring Cloud:分布式系统的“粘合剂”(六)
后端·spring·spring cloud
AI_小站1 天前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
晓晓_za8986681 天前
Geo 优化源码蒸馏词机制:地域词库构建与匹配逻辑详解
运维·tcp/ip·spring·缓存·ci/cd
ycjunhua1 天前
Spring AI 2.0 GA:ToolCallingAdvisor 重构与 Java Agent 新范式
java·人工智能·spring