key-value配对:java Pair<L, R>api使用
当我们在需要返回两种值的情况下可以使用这个api,在核心Java库中可以使用配对(Pair)的实现、Apache Commons。如果原来的项目中jdk低于1.8建议使用Apache Commons这种方法,这样不用动原项目的jdk。
Pair类
Pair类在javafx.util 包中,类构造函数有两个参数,键及对应值:
javafx.util.Pair<Integer, String> pair = new javafx.util.Pair<>(1, "One");
Integer key = pair.getKey();
String value = pair.getValue();
其键和值可以通过标准的getter和setter方法获得。
另外AbstractMap 类还包含一个嵌套类,表示不可变配对:SimpleImmutableEntry 类。
AbstractMap.SimpleImmutableEntry<Integer, String> entry = new AbstractMap.SimpleImmutableEntry<>(1, "one");
应用方式与可变的配对一样,除了配置的值不能修改,尝试修改会抛出UnsupportedOperationException异常。
Apache Commons
maven导入依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
在Apache Commons库中,org.apache.commons.lang3.tuple 包中提供Pair抽象类,不能被直接实例化,可以通过Pair.of(L,R)实例化,提供了getLeft()和getRight()方法。
public class RedisTest {
public static void main(String[] args) {
try {
//不可变配对
Pair<String, String> pair = new ImmutablePair<>("123", "456");
//可变配对
Pair<String, String> pairV2 = new MutablePair<>("123", "456");
//不可变配对set值会抛错
//pair.setValue("123");
pairV2.setValue("123");
System.out.println(pair.getKey());
System.out.println(pair.getValue());
System.out.println(pair.getLeft());
System.out.println(pair.getRight());
System.out.println("-----------");
System.out.println(pairV2.getKey());
System.out.println(pairV2.getValue());
System.out.println(pairV2.getLeft());
System.out.println(pairV2.getRight());
} catch (Exception e) {
e.printStackTrace();
}
}
}
不可变配对ImmutablePair不允许set值