HashMap basics

A HashMap is a data table with a special structure that allows data objects to be found quickly. The position of a data object is defined by a hash function. In the HashMap, the data is stored as key pairs. The values can be accessed via the key. Functions for adding, deleting and modifying elements can be accessed via a HashMap object.


import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<String, Integer>();

HashMap Example

This code defines a class named “HashMapBasics” which creates an instance of the java.util.HashMap class and performs some operations on it.

The class creates a HashMap object map of type String for keys and Integer for values. It adds 4 key-value pairs to the map using the put method: “ProductA” is mapped to 1, “ProductB” is mapped to 2, “ProductC” is mapped to 3, and “ProductD” is mapped to 4.

The code then uses a for loop to iterate over all the keys in the map and outputs the key and its corresponding value using the keySet method to get all the keys and the get method to get the value of a specific key.

The code then updates the value of the key “ProductC” to 8 using the put method and outputs the new value of “ProductC” using the get method.

In summary, this code demonstrates how to create and use a HashMap in Java.

import java.util.HashMap;

public class HashMapBasics {

	public static void main(String[] args) {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		map.put("ProductA", 1);
		map.put("ProductB", 2);
		map.put("ProductC", 3);
		map.put("ProductD", 4);
		for(String name: map.keySet()) {
			System.out.println(name + ": " + map.get(name));
		map.put("ProductC", 8);
		System.out.println("New value for ProductC : " + map.get("ProductC"));
ProductC: 3
ProductD: 4
ProductA: 1
ProductB: 2
New value for ProductC : 8