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"
    }
}
相关推荐
你我约定有三13 小时前
RabbitMQ--消费端异常处理与 Spring Retry
spring·rabbitmq·java-rabbitmq
shuair15 小时前
07 - spring security基于数据库的账号密码
spring·spring security
Java水解15 小时前
深度剖析【Spring】事务:万字详解,彻底掌握传播机制与事务原理
后端·spring
杨杨杨大侠16 小时前
第3篇:配置管理的艺术 - 让框架更灵活
java·spring·log4j
Java码农田17 小时前
springmvc源码分析全体流程图
spring·源码
做一位快乐的码农19 小时前
房屋装修设计管理系统的设计与实现/房屋装修管理系统
java·struts·spring·eclipse·tomcat·maven
麦兜*20 小时前
【Prometheus】 + Grafana构建【Redis】智能监控告警体系
java·spring boot·redis·spring·spring cloud·grafana·prometheus
孟婆来包棒棒糖~1 天前
Maven快速入门
java·spring boot·spring·maven·intellij-idea
知其然亦知其所以然1 天前
SpringAI:Mistral AI 聊天?一文带你跑通!
后端·spring·openai
Warren982 天前
Spring Boot 整合网易163邮箱发送邮件实现找回密码功能
数据库·vue.js·spring boot·redis·后端·python·spring