Mark As Completed Discussion

HashMap and its Implementation

The HashMap class in Java is an implementation of the Map interface and provides a way to store key-value pairs. It allows you to insert, retrieve, and delete elements based on the key.

Creating a HashMap

To create a HashMap, you need to declare a variable of type Map and instantiate it with the HashMap class:

TEXT/X-JAVA
1Map<String, Integer> hashMap = new HashMap<>();

In this example, the String type is used for the keys, and the Integer type is used for the values. You can choose different types for your keys and values based on your requirements.

Adding Elements to a HashMap

You can add elements to a HashMap using the put method. The put method takes two parameters: the key and the value.

TEXT/X-JAVA
1hashMap.put("key", value);

For example, let's add some key-value pairs to the HashMap:

TEXT/X-JAVA
1hashMap.put("one", 1);
2hashMap.put("two", 2);
3hashMap.put("three", 3);

Accessing Elements from a HashMap

You can access elements from a HashMap using the get method. The get method takes the key as a parameter and returns the corresponding value.

TEXT/X-JAVA
1int value = hashMap.get("key");

For example, let's access the values of the key-value pairs we added earlier:

TEXT/X-JAVA
1int value1 = hashMap.get("one");
2int value2 = hashMap.get("two");
3int value3 = hashMap.get("three");

Output

When you run the above code, the output will be:

SNIPPET
1Value of 'one': 1
2Value of 'two': 2
3Value of 'three': 3

You can see that the values are retrieved based on the keys.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment