In Java, a “dictionary” is most commonly implemented using the HashMap class, which stores key-value pairs. This guide shows you how to create, populate, access, and iterate over a dictionary using HashMap, plus how to handle common pitfalls. You’ll need a basic understanding of Java syntax and a development environment (like JDK and an IDE or text editor) to follow along.
What You’ll Need
- Java Development Kit (JDK) 8 or later installed.
- A text editor or IDE (e.g., IntelliJ IDEA, Eclipse, VS Code).
- Basic familiarity with Java classes and methods.
Step-by-Step
- Import the HashMap class. At the top of your Java file, add
import java.util.HashMap;(andimport java.util.Map;if you plan to use theMapinterface). This makes the class available. - Declare and instantiate the dictionary. Choose the key and value types. For example, to map
Stringkeys toIntegervalues:Map<String, Integer> dictionary = new HashMap<>();
Using theMapinterface is a good practice because it allows you to swap implementations later. - Add key-value pairs. Use the
putmethod:dictionary.put("apple", 3);dictionary.put("banana", 5);
If the key already exists,putreplaces the old value and returns the previous value (ornullif new). - Retrieve a value by key. Use
get:Integer count = dictionary.get("apple");
This returnsnullif the key is not present. To avoid null, check withcontainsKeyfirst or usegetOrDefault. - Check if a key or value exists. Use
containsKeyandcontainsValue:if (dictionary.containsKey("banana")) { ... }boolean hasValue = dictionary.containsValue(5); - Remove an entry. Use
remove:dictionary.remove("apple");
This returns the removed value, ornullif the key wasn’t there. - Iterate over the dictionary. Use a for-each loop over
entrySet()to get both keys and values:for (Map.Entry<String, Integer> entry : dictionary.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());}
Alternatively, iterate overkeySet()orvalues()if you only need one side. - Get the size. Use
size()to see how many entries are stored:int total = dictionary.size(); - Clear all entries. Use
clear()to empty the dictionary:dictionary.clear(); - Use default values (optional). To avoid null checks, use
getOrDefault:Integer count = dictionary.getOrDefault("orange", 0);
This returns 0 if “orange” is not a key.
Common Mistakes
- Forgetting to import
java.util.HashMap– causes a compilation error. - Using primitive types like
intinstead of wrapper classesIntegerin generics –HashMapcannot store primitives. - Assuming insertion order –
HashMapdoes not guarantee order. UseLinkedHashMapif you need insertion order, orTreeMapfor sorted order. - Modifying the dictionary while iterating (adding or removing entries) can throw
ConcurrentModificationExceptionunless you use an iterator’sremove()method. - Using mutable objects as keys – if the key’s hash code changes after insertion, the entry becomes unreachable.
Tips
- Use
Map<K, V>as the variable type for flexibility – you can switch toTreeMaporLinkedHashMapwithout changing the rest of the code. - Use
getOrDefaultto provide fallback values and avoid null checks. - When performance matters, initialize with an expected capacity:
new HashMap<>(expectedSize)to reduce resizing overhead. - For thread-safe operations, use
ConcurrentHashMapinstead ofHashMap. - Override
equals()andhashCode()in custom key classes to ensure correct behavior.
Troubleshooting
- Compilation error: “cannot find symbol” – Check the import statement and that you’re using the correct class name (
HashMap). - NullPointerException when calling
get– The key might not exist, sogetreturnsnull. UsecontainsKeyorgetOrDefaultto handle it. - ConcurrentModificationException – You’re modifying the map while iterating. Use an iterator and call
iterator.remove(), or collect keys to remove and delete after the loop. - Unexpected order of entries – Remember
HashMapis unordered. If order matters, switch toLinkedHashMap(insertion order) orTreeMap(sorted by key). - Keys with same hash code – This is normal;
HashMaphandles collisions using equals(). Ensure your key’sequals()is consistent withhashCode().
Frequently Asked Questions
- What is the difference between HashMap and Hashtable?
Hashtable is synchronized (thread-safe) and does not allow null keys or values. HashMap is not synchronized and allows one null key and multiple null values. In modern code, preferConcurrentHashMapfor thread safety. - Can I use a custom object as a key?
Yes, but you must overrideequals()andhashCode()so that equal objects produce the same hash code. Otherwise, lookups may fail. - How do I iterate over a HashMap in Java 8+?
You can use a for-each loop onentrySet(), or use theforEachmethod with a lambda:dictionary.forEach((key, value) -> System.out.println(key + " -> " + value)); - Is HashMap ordered?
No,HashMapdoes not maintain any order. If you need insertion order, useLinkedHashMap. For sorted order by key, useTreeMap. - What happens if I put a duplicate key?
The old value is replaced with the new one, andputreturns the previous value (ornullif it was new). - How can I make a dictionary thread-safe?
UseConcurrentHashMapfromjava.util.concurrent. It provides thread-safe operations without locking the entire map.
Related
- How to Make Balloon Numbers: Step-by-Step Guide
- How to Define an Enum in Java
- How to Set Enum Value in Java (with Code Examples)
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Find a Circular Reference in Excel Step by StepIn Excel for Microsoft 365 on Windows, select Formulas > Error Checking ▼, point to Circular References, then…
- How to Create Email Rules in Outlook 365To create an email rule in Outlook 365, open Settings, go to Mail > Rules, choose Add new…
- Loan Amortization in Excel: Calculate Payments and ScheduleTo calculate loan amortization in Excel, enter the loan amount in B1, annual interest rate in B2, and…
- Federal Reserve Weekly Balance Sheet ExplainedThe Federal Reserve publishes its weekly balance sheet every Thursday at 4:30 p.m. Eastern Time, showing the assets…
- How to Record a PowerPoint Presentation Step by StepTo record a PowerPoint presentation, open the deck in the desktop app, choose Record > From Beginning or…
- How to Add a Header to Just the First Page in WordTo add a header only to page one in Word, open the header, select Different First Page on…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.