HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type. Java HashMap class implements the map interface by using a hash table1.

So, in this we can set the key or the index and value. the both has to be set by us not by the program itself.

So now to declare a hashmap we use

  • HashMap<> // In the bracket, We have to pass similarly what how we pass type in arraylist, which is for the values. but here we would pass two types
  • HashMap <Ty, Ty> The First one would be the type of key we want, and the second one would be the value we want , now you can write it as
  • HashMap <Ty, Ty> name = new HashMap<>();

This is how we declare the HashMap.

The only difference between the List and the HashMap is that we have to pass another type for the key as well.

In this blog you will find how to declare a hashmap, how to add items in the hashmap, how to get data from the hashmap, how to remove an item from hashmap, how to get size of a hashmap, how to get keys of a hashmap and how to get values of a hashmap, How to program with different datatype in Hashmap

You can watch our video related to HashMap, where you can find step wise guide to do operations with Hashmap in Java

Now Let understand with code:

Create a class named as HashMapClass:
import java.util.HashMap;

public class HashMapClass{

public static void main(String[] args){
HashMap<String, String> game = new HashMap<>();
game.put("India", "Hockey");
game.put("England", "Cricket");
game.put("USA", "Baseball");

System.out.println(game);
System.out.println(game.get("USA"));
System.out.println(game.get("India"));

game.remove("England");

System.out.println(game);
System.out.println(game.size());

System.out.println(game.keySet());
System.out.println(game.values());
}
}

Program with different datatype in Hashmap

public class HashMapClass{

public static void main(String[] args){

HashMap<String, Integer> game = new HashMap<>();

game.put(“India”, 1);

game.put(“England”, 2);

game.put(“USA”, 3);

System.out.println(game);


}

}

So what we conclude is that we can use any type of datatype in hashmap and you can work with it. So in java ArrayList and HasMap is basically called Collections. It is a collection of datasets. Here in this video, we collecting datasets of String, String first and then String, Integer… ArrayList and HasMap are the major part of the Collections.

Connect with us: