257

I'm looking for a KeyValuePair class in Java.
Since java.util heavily uses interfaces there is no concrete implementation provided, only the Map.Entry interface.

Is there some canonical implementation I can import? It is one of those "plumbers programming" classes I hate to implement 100x times.

maayank
  • 4,200
  • 2
  • 24
  • 23
  • 4
    I'd recommend against using a generic KeyValuePair class. Much better to define a domain-specific class with more informative accessors (e.g. getProductId(), getProductPrice()). – Adamski Jun 04 '10 at 10:04
  • 25
    @Adamski: I disagree. We don't use domain-specific `Map` or `List` classes, why should this be any different? A KeyValuePair is just a Map with one entry. – skaffman Jun 04 '10 at 10:21
  • 4
    @skaffman: Fair point but I think the concept of a generic Pair is more easily open to abuse than passing Collections around. For example, if someone wants to return two values from a method it's tempting to return a Pair but typically this is indicative of an underlying design problem (e.g. Why aren't X and Y unified somehow anyway in the domain model if they're intrinsically related?) – Adamski Jun 04 '10 at 10:31
  • 13
    @Adamski: Because it's not ``, it's ``. He's not asking for an arbitrary `Pair` type, he's asking for a `KeyValuePair` type. – skaffman Jun 04 '10 at 10:38
  • 3
    Despite this I would much rather pass around a single object instance in my code, potentially with a getKey() method defined; e.g. I prefer: processProduct(Product) to processProduct(KeyValuePair) where the Integer is the product ID. I agree that KeyValuePair (i.e. Map.Entry) or even a generic Pair is useful within a method logic but I don't like it to "leak out" as a return type or be supplied as a method parameter; e.g. I never pass around Map.Entry. – Adamski Jun 04 '10 at 10:52
  • if you are android programmer, just use Intent which has putExtra and GetExtra methods. – MbPCM Jan 03 '22 at 15:26

10 Answers10

272

The class AbstractMap.SimpleEntry is generic and can be useful.

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
  • 12
    ...or AbstractMap.SimpleImmutableEntry if appropriate. – karmakaze Aug 07 '13 at 03:09
  • So I should use `List` correct? – George May 18 '16 at 22:15
  • 2
    Better use AbstractMap.SimpleEntry / AbstractMap.SimpleImmutableEntry as base for your own, domain-specific class, to be OO. In the simplemost case, it is just giving a new name to class and the two elements. – foo Jun 29 '17 at 17:48
  • 2
    In the interest of best practices, it should be noted that in most cases `java.util.Map.Entry` should be used in order to program to interfaces. So you should be using `List>`, for example, for the same reason you wouldn't use `ArrayList>` in the consuming code. The code that actually _creates_ the instance must use a concrete class, obviously. – Garret Wilson Mar 31 '19 at 16:31
111

Android programmers could use BasicNameValuePair

Update:

BasicNameValuePair is now deprecated (API 22). Use Pair instead.

Example usage:

Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
k4dima
  • 6,070
  • 5
  • 41
  • 39
  • 12
    That's not just for Android programmers, it's any java program. – Cody Dec 13 '11 at 12:45
  • 4
    @doctor-oreo yes any java programmer could download jar from [hc.apache.org](http://hc.apache.org/) but android has those **built in** – k4dima Dec 13 '11 at 21:58
  • 34
    Actually for Android users, a good choice is [android.util.Pair](http://developer.android.com/reference/android/util/Pair.html). – chhabrakadabra Apr 04 '12 at 01:43
  • @GalDude33 why is that? It's added in 5 api level. – k4dima Jul 16 '14 at 00:05
  • 2
    This isn't a universally-available language feature and will require more than a standard JRE runtime. `Pair` comes from javafx.util, which introduces a dependency on JavaFX, such as OracleJDK, OpenJDK or OpenJFX. If you're using one of these Java runtimes then great, but there's no trivial way to add this to a JRE installation with a Maven or Gradle dependency. – Brandon Jun 12 '17 at 21:22
54

The Pair class from Commons Lang might help:

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

Of course, you would need to include commons-lang.

remipod
  • 11,269
  • 1
  • 22
  • 25
  • 8
    url changes from time to time. I googled Pair Commons Lang" and found it. I removed the link to prevent further downvotes :-( – remipod Apr 01 '13 at 17:52
  • 2
    Since 1.6 there has been `java.util.AbstractMap.SimpleEntry` - which makes the commons Pair redundant. – Andre Aug 05 '16 at 21:16
  • 2
    I prefer commons Pair personally - doesn't seem right to have to dig for a class inside of AbstractMap. But if you don't want to depend on commons lang for some reason, I could see that. – metaforge Sep 23 '16 at 20:41
14

Use of javafx.util.Pair is sufficient for most simple Key-Value pairings of any two types that can be instantiated.

Pair<Integer, String> myPair = new Pair<>(7, "Seven");
Integer key = myPair.getKey();
String value = myPair.getValue();
aaroncarsonart
  • 1,054
  • 11
  • 27
12
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;
    }
}
Neoheurist
  • 3,183
  • 6
  • 37
  • 55
10

I like to use

Properties

Example:

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

If you are familiar with a hash table you will be pretty familiar with this already

  • Properties are based on HashTable, and for a simple pair a HashTable is probably to expensive – neoexpert Apr 28 '21 at 14:38
  • As long as all you need is `` Properties is best OTS class. If you need ``, then best to back down the chain for a better solution – GoldBishop Oct 17 '21 at 14:51
  • I took a really long break from Java. I messed around with some other keyvalue options awhile but was having issues so I googled for a better idea and ended up here and using my own answer from 5 years ago haha. – Nathan Clark Baumgartner Jun 26 '23 at 20:34
4

You can create your custom KeyValuePair class easily

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;
    }

}
Mohhamed Nabil
  • 4,104
  • 1
  • 15
  • 11
1

My favorite is

HashMap<Type1, Type2>

All you have to do is specify the datatype for the key for Type1 and the datatype for the value for Type2. It's the most common key-value object I've seen in Java.

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

matthewpark319
  • 1,214
  • 1
  • 14
  • 16
  • 2
    You seem to have missed part of his qualifications in this question. A collection does not fit the need of a single key value pair. He mentions the type of single Map entry, `Map.Entry` but wanted a more general case. This type can be instantiated directly though, see this answer: http://stackoverflow.com/a/3110563/3251909 – aaroncarsonart Jan 12 '17 at 20:07
  • Big problem with this is that hashmap does not preserve the order. – Nyerguds Sep 18 '18 at 10:46
-1

I've published a NameValuePair class in GlobalMentor's core library, available in Maven. This is an ongoing project with a long history, so please submit any request for changes or improvements.

Garret Wilson
  • 18,219
  • 30
  • 144
  • 272
  • Can someone explain why this was marked down? The OP asked for a name-value pair class. I provided one option. Perhaps mine is not your favorite, but how is it any less worthy for inclusion here than from from the other libraries indicated in the other answers? (Note that I did however just update the links, as one was broken due to repository reshuffling.) – Garret Wilson Jan 17 '20 at 14:46
-1
Hashtable<String, Object>

It is better than java.util.Properties which is by fact an extension of Hashtable<Object, Object>.

Oleg Mikhailov
  • 5,751
  • 4
  • 46
  • 54