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?
Since version 9, Java has a static method entry() in the Map interface to create an Entry: Map. Entry<String, String> entry = Map. entry("key", "value"); assertThat(entry.
public AbstractMap.SimpleEntry(K key, V value) Creates an entry representing a mapping from the specified key to the specified value. Parameters: key - the key represented by this entry value - the value represented by this entry.
The Java HashMap entrySet() returns a set view of all the mappings (entries) present in the hashmap. The syntax of the entrySet() method is: hashmap.entrySet() Here, hashmap is an object of the HashMap class.
The AbstractMap class is a part of the Java Collection Framework. It directly implements the Map interface to provide a structure to it, by doing so it makes the further implementations easier. As the name suggests AbstractMap is an abstract class by definition, therefore it cannot be used to create objects.
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
.
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:
AbstractMap.SimpleEntry
,AbstractMap.SimpleImmutableEntry
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With