简单的HashMap示例如下所示。 在这个例子中,我们将展示HashMap执行的各种操作:

  • 将键和值添加到HashMap。
  • 通过从HashMap传递键来检索值。
  • 从HashMap中删除键及其值。
  • 获取HashMap的大小。
  • 检查HashMap中是否存在密钥。
  • 检查HashMap中是否存在值。
  • 从HashMap中删除所有键和值。

文件:HashMapExample.java -

package com.yiibai.tutorial;

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

/**
 * @author yiibai
 *
 */
public class HashMapExample {
    public static void main(String[] args) {
        Map<String String> map=new HashMap<>();
        /*Adding key and values in HashMap*/
        map.put("1" "One");
        map.put("2" "Two");
        map.put("3""Three");
        map.put("4" "Four");
        map.put("5" "Five");

        System.out.println("HashMap key-values:"+map);

        /*Get value by key from the HashMap*/
        System.out.println("Value of '4' is: "+map.get("4"));

        /*Removing key and value from the HashMap    */
        map.remove("4");
        System.out.println("After removal HashMap : " +map);

        /*Getting size of HashMap*/
        System.out.println(" Size of HashMap is : "+map.size());

        /*Checking if key exist in the HashMap or not*/
        System.out.println("Key '3' exist: "+map.containsKey("3"));

        /*Checking if value exist in the HashMap or not*/
        System.out.println("Key '6' exist: "+map.containsValue("6"));

        /*Remove all keys and values from the HashMap*/
        map.clear();
        System.out.println("After clearing map: "+map);
    }
}

执行上面代码,得到以下结果:

HashMap key-values:{1=One 2=Two 3=Three 4=Four 5=Five}
Value of '4' is: Four
After removal HashMap : {1=One 2=Two 3=Three 5=Five}
Size of HashMap is : 4
Key '3' exist: true
Key '6' exist: false
After clearing map: {}