How to Create a HashMap in Java?

In Java, you can create a HashMap collection using the following code:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        // 创建HashMap集合
        HashMap<String, Integer> hashMap = new HashMap<>();

        // 添加元素到HashMap集合
        hashMap.put("A", 1);
        hashMap.put("B", 2);
        hashMap.put("C", 3);

        // 打印HashMap集合
        System.out.println(hashMap);
    }
}

In the above code, the java.util.HashMap class is imported first. Then, a HashMap collection named ‘hashMap’ is created in the main method. Key-value pairs are added to the HashMap collection using the put method. Finally, by printing the HashMap collection, the elements in the collection can be seen.

Note that when creating a HashMap collection, you can specify the types of the keys and values. In the above code, a HashMap was used to create a collection with keys of type String and values of type Integer.

bannerAds