Blog
Java program using HashMap to store name and age pairs
Java program using HashMap to store name and age pairs
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();}
}
}