HashMap in Java

Many techies who loves to code in Java would have found Hashmap an interesting Map data structure.

So, basically what is an HashMap? HashMap is an object that has a number of ‘buckets’ which is used to store “key/value” in as pairs.

For example.,

Map=HashMap( Pair( Lion, cub  ), Pair( Goose, gosling ), Pair( Cat, kitten  ), Pair( Duck, duckling ) )

The above Hashmap consists of key-value pairs which are:


KEYS(Unique hash codes) VALUES(Values stored in their respective keys)
Lion cub
Goose gosling
Cat kitten
Duck duckling



Generally, Hashing refers to assigning unique codes for variables based on an algorithm/formula applied to variables.

The HashMap class in java uses a hashtable to implement the Map interface


Let’s see how to code:


import java.util.HashMap;

import java.util.Map;

public class HashMapDemo {

public static void main(String[] args) {

//Create HashMap

Map<String , String> Animal = new HashMap<String, String>();

/ /Add Key/Value pairs

Animal.put(“Lion”, “cub”);

Animal.put(“Goose”, “gosling”);

Animal.put(“Cat”, “kitten”);

Animal.put(“Duck”, “ducking”);

//find element using key

System.out.println(“Younger ones of Lion is called: “+Animal.get(“Lion”));

//remove element


//Iterate over HashMap

for(String key: Animal.keySet()){

System.out.println(key  +” : “+ Animal.get(key));






Younger ones of Lion is called: cub
Duck : ducking
Cat : kitten
Goose : gosling

Any queries, do leave me a comment. Meanwhile let me post more on HashMap and other such trending topics shortly

Latest posts by abirami vijayakumar (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *

займ на карту онлайн круглосуточно