java方法返回多个值,使用Pair、Triple

在编写java代码时,会遇到一个方法中需要返回多个返回值的场景。

比如一个方法中返回两个boolean值,或者返回一个String,一个Integer类型,或者多个对象。

常规我们写一般会用一个对象将这些内容封装起来,然后返回,或者使用Map将他们存起来返回。

这里介绍使用Pair、Triple来实现上述功能。

Pair、Triple

org.apache.commons.lang3 提供了返回多个值的工具类,返回2个值用Pair,3个值用Triple

cn.hutool.core.lang 包中也提供了关于Pair的工具包

以下内容主要基于 commons-lang3 包进行讲解。

在 commons-lang3 包中主要提供了两种Pair类的用法:

一种是Pair<L, R>理解为左边与右边;

一种是Pair<K, V> 键值对key-value的形式;

org.apache.commons.math3.util.Pair

org.apache.commons.math3.util.Pair是Pair<K, V>键值对的形式,提供的方法主要是getKey(),getValue()

1
2
3
4
5
6
7
8
9
10
import org.apache.commons.math3.util.Pair;

public class Test {
public static void main(String[] args) {
//org.apache.commons.math3.util.Pair;
Pair<Boolean,String> pair = new Pair<>(true,"张三");
System.out.println(pair.getKey());
System.out.println(pair.getValue());
}
}

执行结果:

1
2
true
张三

org.apache.commons.lang3.tuple.Pair

org.apache.commons.lang3.tuple.Pair是一个抽象类

提供Pair<L, R>左边与右边的形式的工具类,获取值的方法有getKey(), getValue(),getLeft(),getRight()

1
2
3
4
5
6
7
8
9
10
11
12
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;

public class Test {
public static void main(String[] args) {
Pair<Boolean,String> pair = new ImmutablePair<>(true,"张三");
System.out.println(pair.getKey());
System.out.println(pair.getValue());
System.out.println(pair.getLeft());
System.out.println(pair.getRight());
}
}

执行结果:

1
2
3
4
true
张三
true
张三

org.apache.commons.lang3.tuple.Triple

Triple提供返回三个参数的工具包,Triple也是一个抽象类,以Triple<L, M, R>的形式返回三个参数

1
2
3
4
5
6
7
8
9
10
11
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;

public class Test {
public static void main(String[] args) {
Triple triple = new ImmutableTriple("张三", 11,"男");
System.out.println(triple.getLeft());
System.out.println(triple.getMiddle());
System.out.println(triple.getRight());
}
}

执行结果:

1
2
3
张三
11

本文标题:java方法返回多个值,使用Pair、Triple

文章作者:LiJing

发布时间:2022年07月30日 - 11:45:34

最后更新:2023年06月03日 - 10:01:42

原始链接:https://blog-next.xiaojingge.com/posts/3874661582.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------