java中使用Pair

java中使用Pair本文讨论一种称为 Pair 的数据结构 该结构提供了一种处理简单的键与值关联的简便方法 当我们要从一个方法返回两个值时 对特别有用 jdk 库中提供了 Pair 的简单实现 除此之外 第三方库 例如 Apache Commons 和 Vavr 在各自的 API 中也提供了类似的功能 1 jdk 中的实现

大家好,我是讯享网,很高兴认识大家。

本文讨论一种称为Pair的数据结构,该结构提供了一种处理简单的键与值关联的简便方法,当我们要从一个方法返回两个值时,对特别有用。

jdk库中提供了Pair的简单实现,除此之外,第三方库(例如Apache Commons和Vavr)在各自的API中也提供了类似的功能。

1、jdk中的实现

1)javafx.util.Pair类:

import javafx.util.Pair; Pair<Integer, String> pair = new Pair<>(1, "One"); Integer key = pair.getKey(); String value = pair.getValue();

讯享网

2)java.util.AbstractMap 类:

除了上面的Pair外,还可以使用AbstractMap中的子类SimepleEntry和SimpleImmutableEntry。

讯享网AbstractMap.SimpleEntry<Integer, String> entry = new AbstractMap.SimpleEntry<>(1, "one"); Integer key = entry.getKey(); String value = entry.getValue(); entry.setValue("two");
AbstractMap.SimpleImmutableEntry<Integer, String> entry = new AbstractMap.SimpleImmutableEntry<>(1, "one"); Integer key = entry.getKey(); String value = entry.getValue();

注意:调用SimpleImmutableEntry类的setValue方法会抛出UnsupportedOperationException异常。

注意:无论是SimpleEntry还是SimpleImmutableEntry,都没有setKey方法。


讯享网

2、org.apache.commons.lang3库

该库包含了ImmutablePair 和MutablePair 两个类,如下:

讯享网ImmutablePair<Integer, String> pair = new ImmutablePair<>(2, "Two"); Integer key = pair.getKey(); String value = pair.getValue(); Pair<Integer, String> pair2 = new MutablePair<>(3, "Three"); Integer key2 = pair2.getKey(); String value2 = pair2.getValue(); pair2.setValue("New Three");

此外,还可以通过静态方法来创建Pair,如下:

MutablePair<Boolean, String> of2 = MutablePair.of(false, ""); System.out.println(of2.getKey()+","+of2.getValue()); of2.setValue("22222"); System.out.println(of2.getKey()+","+of2.getValue()); ImmutablePair<Boolean, String> of3 = ImmutablePair.of(false, ""); System.out.println(of3.getKey()+","+of3.getValue()); of3.setValue("22222");//抛异常 System.out.println(of3.getKey()+","+of3.getValue()); Pair<Boolean, String> of = Pair.of(false, ""); System.out.println(of.getKey()+","+of.getValue()); of.setValue("22222");//抛异常 System.out.println(of.getKey()+","+of.getValue());

说明:调用ImmutablePair的setValue方法会抛出UnsupportedOperationException异常。

注意:无论是MutablePair 还是ImmutablePair ,都没有setKey方法。

3、Vavr库:

vavr库是函数式编程的一个库,提供了Tuple2类,如下:

讯享网Tuple2<Integer, String> pair = new Tuple2<>(4, "Four"); Integer key = pair._1(); String value = pair._2();

注:这种方式创建后无法再进行修改,可以调用update1和update2方法,但是会返回一个新的Tuple2对象。

Tuple2<Integer, String> pair = new Tuple2<>(4, "Four"); Integer key = pair._1(); String value = pair._2(); System.out.println(key+","+value);//4,Four Tuple2<Integer, String> update1 = pair.update1(5); System.out.println(update1._1+","+update1._2);//5,Four Tuple2<Integer, String> update2 = pair.update2("Five"); System.out.println(update2._1+","+update2._2);//4,Fivea

来源:https://www.baeldung.com/java-pairs

小讯
上一篇 2025-04-04 15:20
下一篇 2025-03-03 15:07

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/45344.html