Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to create new Entry (key, value)

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?

like image 810
Spiderman Avatar asked Jun 24 '10 13:06

Spiderman


People also ask

How do you create a Map entry in Java?

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.

What is AbstractMap SimpleEntry?

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.

What is entry and entrySet in Java?

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.

What is AbstractMap in Java?

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.


1 Answers

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 new instanceof

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:

  • 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.

like image 192
polygenelubricants Avatar answered Oct 04 '22 15:10

polygenelubricants