Java HashMap Tutorial

HashMaps are Maps that store objects in pairs called Keyset and Values.

Creating the hashmap, this hashmap will be a Contact List

// Create a HashMap , the objects are our Contacts 
HashMap<String, String> Contacts = new HashMap<String, String>();

Here the Keyset and Values are added. For this example , the contact’s Name and Number are being added

Note : the Values are being printed out which would reference the contact’s phone number

// Add keys and values (Name, Number)
Contacts.put("Pat", "123-321");
 Contacts.put("Jan", "321-123");
Contacts.put("Amy", "342-123");
Contacts.put("Mat", "543-123");
System.out.println(Contacts.values());

The Keyset or contact’s Name is being printed out here

 for (String i : Contacts.keySet()) {
		    		  System.out.println("Contact : " +i);
		    
		    	 }}}

remove() can be used to remove objects from map

Contacts.remove("Pat");

get() is used to select certain objects from the hashmap

Contacts.get("Mat");

clear() is used to erase all objects from hashmap

Contacts.clear()

Printing out the entire Contact List HashMap

for (String i : Contacts.keySet()) {
		        System.out.println("Name: " + i + " Number: " + Contacts.get(i));
Output
Name: Mat Number: 543-123
Name: Pat Number: 123-321
Name: Jan Number: 321-123
Name: Amy Number: 342-123
Full code
package Example;
import java.util.HashMap; 

public class example {
	
	public static void main(String[] args) {
		 
		    // Create a HashMap with object called Contacts 
		    HashMap<String, String> Contacts = new HashMap<String, String>();

		    // Add keys and values (Name, Number)
		    Contacts.put("Pat", "123-321");
		    Contacts.put("Jan", "321-123");
		    Contacts.put("Amy", "342-123");
		    Contacts.put("Mat", "543-123");
		    System.out.println(Contacts.values());
		    
	    for (String i : Contacts.keySet()) {
		        System.out.println("Name: " + i + " Number: " + Contacts.get(i));
		    	 }}}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s