Java中的KeyValuePair

我正在寻找Java中的KeyValuePair类 因为java。util大量使用接口,没有提供具体的实现,只有Map。输入接口。< / p >

是否有我可以导入的规范实现? 这是一个“水管工编程”类,我讨厌实现100次

442078 次浏览

AbstractMap。SimpleEntry类是泛型的,可能很有用。

Android程序员可以使用BasicNameValuePair

更新:

BasicNameValuePair现在已弃用(API 22)。 使用一对代替

使用示例:

Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"

Commons Lang中的Pair类可能会有所帮助:

Pair<String, String> keyValue = new ImmutablePair("key", "value");

当然,您需要包括commons-lang。

import java.util.Map;


public class KeyValue<K, V> implements Map.Entry<K, V>
{
private K key;
private V value;


public KeyValue(K key, V value)
{
this.key = key;
this.value = value;
}


public K getKey()
{
return this.key;
}


public V getValue()
{
return this.value;
}


public K setKey(K key)
{
return this.key = key;
}


public V setValue(V value)
{
return this.value = value;
}
}

使用javafx.util.Pair对于任何两种可以实例化的类型的大多数简单键-值对都足够了。

Pair<Integer, String> myPair = new Pair<>(7, "Seven");
Integer key = myPair.getKey();
String value = myPair.getValue();

我最喜欢的是

HashMap<Type1, Type2>

您所要做的就是为Type1指定键的数据类型,为Type2指定值的数据类型。这是我在Java中见过的最常见的键值对象。

https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

我已经在GlobalMentor的核心库中发布了一个NameValuePair类,在Maven中可用。这是一个有很长历史的正在进行的项目,所以请提交任何更改或改进的请求。

我喜欢用

Properties .

例子:

Properties props = new Properties();


props.setProperty("displayName", "Jim Wilson"); // (key, value)


String name = props.getProperty("displayName"); // => Jim Wilson


String acctNum = props.getProperty("accountNumber"); // => null


String nextPosition = props.getProperty("position", "1"); // => 1

如果你熟悉哈希表,你就会对这个很熟悉

Hashtable<String, Object>

它比java.util.Properties更好,后者实际上是Hashtable<Object, Object>的扩展。

您可以轻松地创建自定义KeyValuePair类

public class Key<K, V>{


K key;
V value;


public Key() {


}


public Key(K key, V  value) {
this.key = key;
this.value = value;
}


public void setValue(V value) {
this.value = value;
}
public V getValue() {
return value;
}


public void setKey(K key) {
this.key = key;
}
public K getKey() {
return key;
}


}