A HashMap
is a class in the Java Collections Framework that implements the Map
interface and stores key-value pairs. It uses a hash table to store the elements, which allows for fast lookups, insertions, and deletions based on the key.
Here is an example of how to create a HashMap
in Java:
HashMap<String, Integer> map = new HashMap<>();
In this example, the map
variable is a HashMap
object that maps strings to integers. The HashMap
class has two generic type parameters: the type of the keys (String
in this case) and the type of the values (Integer
in this case).
You can add elements to the HashMap
using the put
method.
For example:
map.put("apple", 1); map.put("banana", 2); map.put("orange", 3);
To get the value of an element in the HashMap
, you can use the get
method and specify the key of the element.
For example:
int value = map.get("apple"); // returns 1
You can use the size
method of the HashMap
class to get the number of elements in the map.
For example:
int size = map.size(); // returns 3
You can use the isEmpty
method of the HashMap
class to check if the map is empty.
For example:
if (map.isEmpty()) { // the map is empty }
You can use the clear
method of the HashMap
class to remove all the elements from the map.
For example:
map.clear(); // removes all the elements from the map
You can use the keySet
method of the HashMap
class to get a Set
of the keys in the map.
For example:
Set<String> keys = map.keySet();
You can use the values
method of the HashMap
class to get a collection of the values in the map.