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;
}
}
结果打印