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"
    }
}
相关推荐
码云数智-园园4 天前
C++20 Modules 模块详解
java·开发语言·spring
咖啡八杯4 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
Flittly5 天前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
李少兄5 天前
从原理到实战:Spring IoC/DI 核心知识体系与高频面试题全解
java·后端·spring
shushangyun_5 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
ofoxcoding5 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
一杯奶茶¥5 天前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目
摇滚侠5 天前
SpringMVC 入门到实战 RESTFul 49-55
java·开发语言·后端·spring·intellij-idea·restful
我登哥MVP5 天前
SpringCloud Alibaba 核心组件解析:服务链路追踪
java·spring boot·后端·spring·spring cloud·java-ee·maven
Ysouy5 天前
Spring Data Elasticsearch 全流程学习教程
java·spring·elasticsearch