java一个方法返回多个对象

该博客展示了如何在Java中通过Apache Commons Lang3库的Pair和Triple类来方便地一次性返回多个对象,以及与传统Map返回方式的对比。示例代码包括创建Pair和Triple对象,并在主函数中打印其内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、导入pom.xml

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>

2、代码编写加测试

package com.lezu.springboot.test;


import cn.hutool.core.map.MapUtil;
import com.lezu.springboot.entity.ShopTree;
import com.lezu.springboot.entity.User;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;

import java.util.Map;

public class Test5{
    public static void main(String[] args) {
        //使用Pair进行返回
        Pair<User, ShopTree> data1 = getData1();
        System.out.println(data1.getKey());
        System.out.println(data1.getValue());

        System.out.println("-----------------------------------------------------");

        //使用Triple进行返回
        Triple<User, ShopTree, String> data2 = getData2();
        System.out.println(data2.getLeft());
        System.out.println(data2.getMiddle());
        System.out.println(data2.getRight());


        System.out.println("-----------------------------------------------------");

        //使用传统的Map进行返回
        Map<String, Object> data3 = getData3();
        User user = (User) data3.get("user");
        ShopTree shopTree = (ShopTree) data3.get("shopTree");
        System.out.println(user);
        System.out.println(shopTree);
    }


    /**
     * 一次性返回2个对象
     * @return
     */
    private static Pair<User,ShopTree> getData1(){
        User user = new User();
        user.setUserName("小王");
        ShopTree shopTree = new ShopTree();
        shopTree.setCatId("1");
        return ImmutablePair.of(user,shopTree);
    }

    /**
     * 一次性返回3个对象
     * @return
     */
    private static Triple<User,ShopTree, String> getData2(){
        User user = new User();
        user.setUserName("小王");
        ShopTree shopTree = new ShopTree();
        shopTree.setCatId("1");
        return ImmutableTriple.of(user,shopTree,"我是张三");
    }

    /**
     * 最传统使用map来进行返回
     * @return
     */
    private static Map<String,Object> getData3(){
        Map<String, Object> map = MapUtil.newHashMap();
        map.put("user",new User());
        map.put("shopTree",new ShopTree());
        return map;
    }
}

结果打印

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值