Add elements to HashMap

In this post, we have seen about HashMap. In this post, we will learn how to add elements to HashMap.

We need to use method put to add the values to HashMap.

Syntax:

HashMap<key, value> hm = new HashMap<key, value>();

Example:

In this example, we will create key of integer and value of String type. Then we need to use put method to add the elements.

import java.util.HashMap;

public class HashMapEx {

	public static void  main(String[] args){
		
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		hm.put(1, "Mobile");
		hm.put(6, "TV");
		hm.put(10, "Laptop");
		hm.put(2, "Desktop");
		hm.put(15, "Tablet");
		
		System.out.println(hm);
	}
}

Output:

{1=Mobile, 2=Desktop, 6=TV, 10=Laptop, 15=Tablet}


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...