Explain Codes LogoExplain Codes Logo

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

java
map-implementation
generics
collections
Anton ShumikhinbyAnton Shumikhin·Feb 26, 2025
TLDR

To encapsulate a key-value pair in Java, leverage AbstractMap.SimpleEntry:

Map.Entry<String, Integer> entry = new AbstractMap.SimpleEntry<>("key", 1);

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():

Map.Entry<String, Integer> immutableEntry = Map.entry("key", 1);

Mutable vs Immutable Entries

The AbstractMap.SimpleEntry, lets you modify the key and value even after instantiation:

entry.setValue(5000); // Whoa, that's a sudden increase in value! 💸

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:

ArrayList<Map.Entry<Integer, String>> listOfEntries = new ArrayList<>(); listOfEntries.add(new AbstractMap.SimpleEntry<>(10, "Ten")); listOfEntries.add(new AbstractMap.SimpleEntry<>(20, "Twenty"));

Just like taking items from a shopping list, you can access each pair using get().getKey() or get().getValue():

int firstKey = listOfEntries.get(0).getKey(); // Hmm, the magic number 10 String firstValue = listOfEntries.get(0).getValue(); // Half of twenty!

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:

Map.Entry<Integer, List<String>> genericEntry = new AbstractMap.SimpleEntry<>(42, Arrays.asList("Answer", "Universe"));

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:

public class MyEntry<K, V> implements Map.Entry<K, V> { // Let's go wild with constraints and functionalities here }

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<String, String> map = Map.of("key1", "value1", "key2", "value2");

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!