HashMap
Pramuditha Madura
Bachelor of Technology - BTech at Open University of Sri Lanka. Undergraduate
A HashMap is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values. In a hash table, the keys are hashed into a number of buckets, and the values are stored in the corresponding buckets. This allows for fast lookups of values by key.
The HashMap class in Java provides a generic implementation of a hash table. The keys and values in a HashMap can be of any type, as long as they are comparable. The HashMap class also provides a number of methods for adding, removing, and iterating over the keys and values in the map.
Here is an example of how to create a HashMap in Java:
HashMap<String, Integer> numbers = new HashMap<>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", 3);
System.out.println(numbers.get("one")); // Prints 1
Here is an example of how to iterate over the keys and values in a HashMap in Java:
for (String key : numbers.keySet()) {
System.out.println(key + " = " + numbers.get(key));
}
This code will print the following output:
one = 1
two = 2
three = 3
HashMaps are a powerful data structure that can be used to store and retrieve data quickly and efficiently. They are often used in applications where it is necessary to quickly find a value given its key, such as in a search engine or a database.