Java - How to create new Entry (key, value)
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Java, an entry is a key-value pair, usually represented by Map.Entry. Most of the time you do not create one directly because calling put on a Map is enough. But there are still cases where a standalone entry object is useful, especially in immutable maps, stream pipelines, or temporary transformations.
The Most Common Case: Put into a Map
If your real goal is just to store a key and value in a map, create the map and call put.
This is usually the correct answer because the map implementation manages its own internal entry objects. You do not need to create one manually first.
Create an Entry with Map.entry
If you really do want a standalone entry object, Java 9 added Map.entry.
This is compact and useful, but it creates an immutable entry. It is ideal for constants, stream code, and Map.ofEntries.
For example:
The resulting map is immutable too, which is often exactly what you want for fixed data.
Use SimpleEntry for a Mutable Entry
If you need a standalone entry object whose value can change, use AbstractMap.SimpleEntry.
There is also AbstractMap.SimpleImmutableEntry if you want the same idea without allowing updates.
Entries Are Useful in Streams
A common modern use case is building entries temporarily in a stream before collecting them into a map.
This is a strong use case for Map.entry because it lets you produce a pair without inventing a helper class just for one stream transformation.
Know When a Custom Type Is Better
Sometimes developers ask for Map.Entry when the pair is really domain data. If the values have business meaning, a custom type is usually clearer.
Use Map.Entry when you genuinely mean "some key associated with some value." Use a record or class when the pair represents something richer.
Common Pitfalls
- Creating a standalone entry when
map.put(key, value)was all you needed. - Expecting
Map.entryto be mutable. It is not. - Creating an entry object and assuming it automatically inserts itself into a map.
- Using
Map.ofEntriesand then trying to callputlater on the returned map. - Collecting stream entries into a map without handling duplicate keys.
Summary
- If you just want to add data to a map, use
map.put(key, value). - Use
Map.entryfor a compact immutable key-value pair. - Use
AbstractMap.SimpleEntrywhen you need a mutable standaloneMap.Entry. - Entries are especially useful in stream transformations and immutable map creation.
- If the pair represents real domain data, a custom record or class is often clearer than a map entry.

