Site icon TestingDocs.com

Write a java program using HashMap to store name and age pairs and print the details?

Introduction

In this tutorial, we will learn to use HashMap to store name and age pairs. HashMap maps keys to values. It implements the Map interface. HashMap is not synchronized and permits nulls. Furthermore, it makes no guarantee as to the order of the map.

In the below sample program, we will store the name/age pair and later display the data stored. One important thing to notice is that you can’t have duplicates in the keys.

If multiple threads access a hash map concurrently, and if threads modify the map you need to synchronize externally. to avoid ConcurrentModificationException.

Java program

import java.util.HashMap;
import java.util.Scanner;

public class HashMapExample {
    public static void main(String[] args) {

        Scanner input = null;
        String name;
        int age ;
        HashMap<String, Integer> hMap = new HashMap<String, Integer>();
        try {
            input=new Scanner(System.in);
            System.out.println("Build HashMap with Details:");
            while (input.hasNext()) {
                name = input.next();
                age = input.nextInt();
                hMap.put(name,age);
            }
            System.out.println("HashMap with Details:");
            hMap.forEach((Name,Age) -> System.out.println("Name: "+Name+
" Age:"+ Age));
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally
        {
            if(input!=null)
            {input.close();}
        }

    }

}

 

Output of the program

Build HashMap with Details:
Albert
23
Regan
38
Brenda
29
Jesse
31
^D
HashMap with Details:
Name: Regan Age:38
Name: Brenda Age:29
Name: Jesse Age:31
Name: Albert Age:23

 

 

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

More information on Java can be found on the official website:

https://www.oracle.com/in/java/

Exit mobile version