Java HashMap
A HashMap
is an important part of the Java collections framework and implements the Map
interface. It stores items as key-value pairs, where each key is unique and is used to fetch the associated value. It is one of the most commonly used data structures for storing key-value pairs. It offers fast lookups, insertions, and deletions, making it an excellent choice for many programming tasks where performance matters.
Key characteristics:
- Null Support: Allows a single
null
key and multiplenull
values. - Order: Does not maintain any insertion or sorted order of elements.
- Thread Safety: Not synchronized by default; not safe for concurrent access without external synchronization.
- Performance: Provides constant-time performance for
.get()
and.put()
operations in average cases. - Key Uniqueness: Keys must be unique; inserting a duplicate key will overwrite the existing value.
Creating a HashMap
The HashMap
class in Java is part of the java.util
package:
import java.util.HashMap;
HashMap<KeyDataType, ValueDataType> myHashMap = new HashMap<KeyDataType, ValueDataType>();
In the syntax:
KeyDataType
: The data type of the keys to be inserted.ValueDataType
: The data type of the values to be inserted.
Accessing Items in a HashMap
The .get()
method can be used to access the value of a key in a HashMap
.
Syntax
hashmap_name.get(key);
Parameters:
key
: The key whose value is to be accessed.
Return value:
The .get()
method returns the value of the given key.
Example
This example demonstrates the usage of the .get()
method to access the value of a key in a HashMap
:
import java.util.HashMap;public class Main {public static void main(String[] args) {// Create a HashMapHashMap<String, String> courseTeacher = new HashMap<String, String>();// Add items to the HashMapcourseTeacher.put("History", "Ben");courseTeacher.put("Mathematics", "Jeanette");courseTeacher.put("Physics", "Lily");// Access the value of a keySystem.out.println(courseTeacher.get("Physics"));}}
Here is the output:
Lily
Adding Items to a HashMap
The .put()
method is used to add items to a HashMap
.
Syntax
hashmap_name.put(key, value);
Parameters:
key
: The key to be added.value
: The value for the key to be added.
Example
This example demonstrates the usage of the .put()
method to add items to a HashMap
:
import java.util.HashMap;public class Main {public static void main(String[] args) {// Create a HashMapHashMap<String, String> courseTeacher = new HashMap<String, String>();// Add items to the HashMapcourseTeacher.put("History", "Ben");courseTeacher.put("Mathematics", "Jeanette");courseTeacher.put("Physics", "Lily");// Print the HashMapSystem.out.println(courseTeacher);}}
Here is the output:
{Mathematics=Jeanette, History=Ben, Physics=Lily}
Removing Items from a HashMap
There are two methods that can be used to remove items from a HashMap
:
.remove()
: This method can be used to delete an item from aHashMap
..clear()
: This method can be used to delete all items from aHashMap
.
Syntax
Here is the syntax for these methods:
hashmap_name.remove(key);
hashmap_name.clear();
Parameters:
key
: The key to be deleted along with its value.
Example
This example demonstrates the usage of the .remove()
and .clear()
methods to delete items from a HashMap
:
import java.util.HashMap;public class Main {public static void main(String[] args) {// Create a HashMapHashMap<String, String> courseTeacher = new HashMap<String, String>();// Add items to the HashMapcourseTeacher.put("History", "Ben");courseTeacher.put("Mathematics", "Jeanette");courseTeacher.put("Physics", "Lily");// Remove an item from the HashMapcourseTeacher.remove("Physics");// Print the HashMapSystem.out.println(courseTeacher);// Remove all items from the HashMapcourseTeacher.clear();// Print the HashMapSystem.out.println(courseTeacher);}}
Here is the output:
{Mathematics=Jeanette, History=Ben}{}
Iterating Over a HashMap
There are three methods that can be used to iterate over a HashMap
:
.keySet()
: Used to iterate over the keys in aHashMap
..values()
: Used to iterate over the values in aHashMap
..entrySet()
: Used to iterate over the items in aHashMap
.
Syntax
Here is the syntax for these methods:
hashmap_name.keySet();
hashmap_name.values();
hashmap_name.entrySet();
Example
This example demonstrates the usage of the for-each
loop to iterate over a HashMap
:
import java.util.HashMap;import java.util.Map;public class Main {public static void main(String[] args) {// Create a HashMapHashMap<String, String> courseTeacher = new HashMap<String, String>();// Add items to the HashMapcourseTeacher.put("History", "Ben");courseTeacher.put("Mathematics", "Jeanette");courseTeacher.put("Physics", "Lily");// Iterate over the keys in the HashMapfor (String i : courseTeacher.keySet()) {System.out.println(i);}// Iterate over the values in the HashMapfor (String i : courseTeacher.values()) {System.out.println(i);}// Iterate over the items in the HashMapfor (Map.Entry<String, String> entry: courseTeacher.entrySet()) {System.out.print(entry);System.out.print("\n");}}}
In the example, Map.Entry
is a nested interface within the Map
interface that represents a key-value pair stored in a map.
Here is the output:
MathematicsHistoryPhysicsJeanetteBenLilyMathematics=JeanetteHistory=BenPhysics=Lily
Frequently Asked Questions
1. How does a HashMap
work internally?
A HashMap
uses an array of buckets, and each bucket is a linked list or a balanced tree (from Java 8 onward). Keys are hashed to determine the bucket index, and values are stored accordingly.
2. Is HashMap
thread-safe?
No. HashMap
is not synchronized. For thread-safe operations, use Collections.synchronizedMap()
or ConcurrentHashMap
.
3. How to increase the performance of a HashMap?
- Choose an appropriate initial capacity and load factor.
- Use immutable keys with properly implemented
hashCode()
andequals()
methods.
HashMap
- .put()
- Inserts or updates a key-value pair in the map.
All contributors
- KyraThompson
- StevenSwiniarski
- Anonymous contributor
- Anonymous contributor
- Sriparno08
- maxjeffrey
- TyCherms18
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours