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?
Example of AbstractMap.SimpleEntry:
Instantiate:
Add rows:
Fetch rows:
Should print:
It's good for defining edges of graph structures. Like the ones between neurons in your head.
You can just implement the
Map.Entry<K, V>
interface yourself:And then use it:
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:
As it is immutable, calling
setValue
will throw anUnsupportedOperationException
. The other limitations are the fact that it is not serializable andnull
as key or value is forbidden, if it is not acceptable for you, you will need to useAbstractMap.SimpleImmutableEntry
orAbstractMap.SimpleEntry
instead.You could actually go with:
Map.Entry<String, String> en= Maps.immutableEntry(key, value);
Try Maps.immutableEntry from Guava
This has the advantage of being compatible with Java 5 (unlike
AbstractMap.SimpleEntry
which requires Java 6.)Why
Map.Entry
? I guess something like a key-value pair is fit for the case.Use
java.util.AbstractMap.SimpleImmutableEntry
orjava.util.AbstractMap.SimpleEntry