Java - How to create new Entry (key, value)
To encapsulate a key-value pair in Java, leverage AbstractMap.SimpleEntry
:
This succinctly creates an Entry object holding the key "key" and value 1.
If you desire an immutable pair, Java 9 and upwards offer Map.entry()
:
Mutable vs Immutable Entries
The AbstractMap.SimpleEntry
, lets you modify the key and value even after instantiation:
However, Map.entry()
returns an immutable entry, so trying to change the value will cause a UnsupportedOperationException
. So no luck here with get-rich-quick schemes!
Exploring collection possibilities
ArrayList
can conveniently store multiple key-value pairs:
Just like taking items from a shopping list, you can access each pair using get().getKey()
or get().getValue()
:
Such implementation can be pretty useful in representing graph structures or relationships.
Generically key and value types
Thanks to generics, keys and values can be of any type, adding greater flexibility and type safety:
A good practice to ensure the integrity of keys and values when they're complex data types like List
or your own class types.
Tailoring your own Entry
When predefined entries are not enough, you can create your own Map.Entry
:
A personalized Map.Entry
allows for extra functionality or constraints. Like the saying: If the shoe doesn't fit, build your own one!
Alternatives to ponder
Consider Guava library's Maps.immutableEntry
compatible with older Java versions, or Map.of()
for creating immutable map collections in Java 9:
Map.of()
and Map.entry()
create entries that are sadly not serializable and do not support the setValue
operation. So remember, the magic set spell is ineffective here!
Was this article helpful?