Java - How to create new Entry (key, value)
There's public static class AbstractMap.SimpleEntry<K,V>
. Don't let the Abstract
part of the name mislead you: it is in fact NOT an abstract
class (but its top-level AbstractMap
is).
The fact that it's a static
nested class means that you DON'T need an enclosing AbstractMap
instance to instantiate it, so something like this compiles fine:
Map.Entry<String,Integer> entry = new AbstractMap.SimpleEntry<String, Integer>("exmpleString", 42);
As noted in another answer, Guava also has a convenient static
factory method Maps.immutableEntry
that you can use.
You said:
I can't use
Map.Entry
itself because apparently it's a read-only object that I can't instantiate newinstanceof
That's not entirely accurate. The reason why you can't instantiate it directly (i.e. with new
) is because it's an interface Map.Entry
.
Caveat and tip
As noted in the documentation, AbstractMap.SimpleEntry
is @since 1.6
, so if you're stuck to 5.0, then it's not available to you.
To look for another known class that implements Map.Entry
, you can in fact go directly to the javadoc. From the Java 6 version
Interface Map.Entry
All Known Implementing Classes:
Unfortunately the 1.5 version does not list any known implementing class that you can use, so you may have be stuck with implementing your own.
Starting from Java 9, there is a new utility method allowing to create an immutable entry which is Map#entry(Object, Object)
.
Here is a simple example:
Entry<String, String> entry = Map.entry("foo", "bar");
As it is immutable, calling setValue
will throw an UnsupportedOperationException
. The other limitations are the fact that it is not serializable and null
as key or value is forbidden, if it is not acceptable for you, you will need to use AbstractMap.SimpleImmutableEntry
or AbstractMap.SimpleEntry
instead.
NB: If your need is to create directly a Map
with 0 to up to 10 (key, value) pairs, you can instead use the methods of type Map.of(K key1, V value1, ...)
.
You can just implement the Map.Entry<K, V>
interface yourself:
import java.util.Map;final class MyEntry<K, V> implements Map.Entry<K, V> { private final K key; private V value; public MyEntry(K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { V old = this.value; this.value = value; return old; }}
And then use it:
Map.Entry<String, Object> entry = new MyEntry<String, Object>("Hello", 123);System.out.println(entry.getKey());System.out.println(entry.getValue());