HashMap in Java with Examples

Spread the love

HashMap in Java with Examples

HashMap is similar to the HashTable, but it is unsynchronized.
It allows to store the null keys as well, but there should be only
one null key object and there can be any number of null values.
This class makes no guarantees as to the order of the map.
To use this class and its methods,
you need to import java.util.HashMap package or its superclass.

// Java program to illustrate
// Java.util.HashMap

import java.util.HashMap;

public class GFG {

public static void main(String[] args)
// Create an empty hash map
HashMap map = new HashMap<>();

// Add elements to the map
map.put(“vishal”, 10);
map.put(“sachin”, 30);
map.put(“vaibhav”, 20);

// Print size and content
System.out.println(“Size of map is:- ”
+ map.size());

// Check if a key is present and if
// present, print value
if (map.containsKey(“vishal”)) {
Integer a = map.get(“vishal”);
System.out.println(“value for key”
+ ” \”vishal\” is:- ” + a);

HashMap in Java with Examples

Scroll to top