Hi everyone, welcome back. In this tutorial, we will be going over HashMaps in Java. HashMaps can be used to store a collection similar to an ArrayList, but the main difference is that HashMaps stores elements as key/value pairs rather than using index numbers. With this introduction out of the way, let’s get into it.
Creating HashMap
Let’s start by creating a HashMap. Before we can create the HashMap, we need to make sure that we have our HashMaps import, which is included within the java.util package:
import java.util.HashMap;
Now, we can successfully create our HashMap:
HashMap<Integer, String> myHashMap = new HashMap<Integer, String>();
So now, we have created a HashMap variable. Our key is of the Integer data type and our value is of the String data type. When we create our HashMap, we need to specify the data type of our keys and values. We can use other data types as well for both the key and value.
Adding Elements Into The HashMap
Now, let’s try to add elements into our HashMap. We can do this by using the built in put() function that is provided. Let’s see an example:
HashMap<Integer, String> myHashMap = new HashMap<Integer, String>()…