Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Java HashMap: A Comprehensive Guide

Java HashMap: A Comprehensive Guide

In Java, a HashMap stores data as key‑value pairs, enabling fast retrieval of values by unique keys. Unlike arrays, the keys can be any object (except null), and the map automatically manages hashing and collision resolution.

Key Features

Declaring a HashMap

HashMap<String, Object> map = new HashMap<String, Object>();
HashMap x = new HashMap();

Essential Methods

Practical Example

Below is a complete, runnable snippet that demonstrates common operations:

import java.util.HashMap;
import java.util.Map;

public class SampleTestMaps {
    public static void main(String[] args) {
        Map<String, String> objMap = new HashMap<>();
        objMap.put("Name", "Suzuki");
        objMap.put("Power", "220");
        objMap.put("Type", "2-wheeler");
        objMap.put("Price", "85000");

        System.out.println("Elements of the Map:");
        System.out.println(objMap);
    }
}

Output:

{Type=2-wheeler, Price=85000, Power=220, Name=Suzuki}

Removing a Specific Entry

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Java");
        map.put(2, "Python");
        map.put(3, "PHP");
        map.put(4, "SQL");
        map.put(5, "C++");

        System.out.println("Before removal: " + map);
        map.remove(5);
        System.out.println("After removal: " + map);
    }
}

Output:

Before removal: {1=Java, 2=Python, 3=PHP, 4=SQL, 5=C++}
After removal: {1=Java, 2=Python, 3=PHP, 4=SQL}

Quick Reference

With these fundamentals, you can confidently integrate HashMaps into any Java application for efficient data storage and retrieval.

Java

  1. Encapsulation in Java: A Comprehensive Guide with Practical Example
  2. Understanding Java Classes and Objects: Clear Concepts, Practical Examples
  3. Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
  4. Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
  5. Command‑Line Arguments in Java: A Practical Guide with Code Examples
  6. Java Inheritance Explained: Types, Syntax, and Practical Examples
  7. Java Abstraction: Mastering Abstract Classes, Methods, and Practical Examples
  8. Understanding Java's throws Keyword: Examples & Best Practices
  9. Java Switch‑Case Statement Explained: Syntax, Examples, and Best Practices
  10. Mastering Java's split() Method: A Practical Guide with Code Examples