Using HashMap in Java

The HashMap in Java belongs to the Java Collections Framework (JCF) and resides in the "java.util" package. It offers a fundamental representation of the Map interface, facilitating the storage of pairs of keys and values. The key undergoes hashing, and this resultant hash acts as an index where the corresponding value gets stored. To employ a HashMap, you should create an instance with a format resembling HashMap<KeyType, ValueType>. Once set up, you can add items to the HashMap via the put method, fetch values with the get method by giving the key, and verify the presence of a key using the containsKey method. The remove method aids in discarding an entry using its key. To cycle through a HashMap, you can apply a for-each loop on its entry set or leverage the keySet and values methods to correspondingly get the sets of keys and values. It's also crucial to recognize that HashMap doesn’t preserve any sequence of its keys or values and permits one null key alongside multiple null values. In this Java HashMap Example, we construct a HashMap, populate it, and then display the content using a loop. Click Execute to run the Java HashMap Example online and see the result.
Using HashMap in Java Execute
import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> studentGrades = new HashMap<>();

        studentGrades.put("Alice", 85);
        studentGrades.put("Bob", 90);

        for (String student : studentGrades.keySet()) {
            System.out.println(student + " scored: " + studentGrades.get(student));
Updated: Viewed: 70 times