0
0
JavaHow-ToBeginner · 4 min read

How to Create HashMap in Java: Syntax and Examples

To create a HashMap in Java, import java.util.HashMap and instantiate it using new HashMap<KeyType, ValueType>(). This creates a collection that stores key-value pairs for fast data retrieval.
📐

Syntax

The basic syntax to create a HashMap is:

  • HashMap<KeyType, ValueType>: Defines the types of keys and values stored.
  • new HashMap<>(): Creates a new empty HashMap instance.
java
HashMap<KeyType, ValueType> map = new HashMap<>();
💻

Example

This example shows how to create a HashMap, add key-value pairs, and print the map.

java
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("apple", 3);
        map.put("banana", 5);
        map.put("orange", 2);

        System.out.println("HashMap contents: " + map);
    }
}
Output
HashMap contents: {orange=2, banana=5, apple=3}
⚠️

Common Pitfalls

Common mistakes when creating or using HashMaps include:

  • Not importing java.util.HashMap, causing compilation errors.
  • Using raw types without specifying key and value types, which leads to warnings and unsafe code.
  • Assuming HashMap maintains insertion order; it does not. Use LinkedHashMap if order matters.
  • Using mutable objects as keys without proper hashCode() and equals() implementations.
java
/* Wrong: raw type usage */
HashMap map = new HashMap(); // Avoid raw types

/* Right: specify types */
HashMap<String, Integer> map = new HashMap<>();
📊

Quick Reference

OperationSyntaxDescription
Create HashMapHashMap map = new HashMap<>();Creates an empty HashMap.
Add entrymap.put(key, value);Adds or updates a key-value pair.
Get valuemap.get(key);Retrieves value by key, or null if not found.
Check keymap.containsKey(key);Checks if key exists.
Remove entrymap.remove(key);Removes key and its value.

Key Takeaways

Use HashMap<KeyType, ValueType> to create a map with specific key and value types.
Always import java.util.HashMap before using it.
HashMap does not keep the order of entries; use LinkedHashMap if order matters.
Avoid raw types to prevent unsafe code and warnings.
Use put() to add entries and get() to retrieve values.