I'd like to create new item that similarly to Util.Map.Entry
that will contain the structure key
, value
.
The problem is that I can't instantiate a Map.Entry
because it's an interface.
Does anyone know how to create a new generic key/value object for Map.Entry?
org.apache.commons.lang3.tuple.Pair
implementsjava.util.Map.Entry
and can also be used standalone.Also as others mentioned Guava's
com.google.common.collect.Maps.immutableEntry(K, V)
does the trick.I prefer
Pair
for its fluentPair.of(L, R)
syntax.If you are using Clojure, you have another option:
I defined a generic Pair class that I use all the time. It's great. As a bonus, by defining a static factory method (Pair.create) I only have to write the type arguments half as often.
There's
public static class AbstractMap.SimpleEntry<K,V>
. Don't let theAbstract
part of the name mislead you: it is in fact NOT anabstract
class (but its top-levelAbstractMap
is).The fact that it's a
static
nested class means that you DON'T need an enclosingAbstractMap
instance to instantiate it, so something like this compiles fine:As noted in another answer, Guava also has a convenient
static
factory methodMaps.immutableEntry
that you can use.You said:
That's not entirely accurate. The reason why you can't instantiate it directly (i.e. with
new
) is because it's aninterface 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 versionUnfortunately 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.