Java HashMap示例

本文介绍了Java HashMap的基本用法,包括添加、获取、更新和删除元素,以及如何进行循环遍历。还强调了在多线程环境下使用HashMap时需要同步的重要性,并给出了Collections.synchronizedMap的例子。
摘要由CSDN通过智能技术生成

HashMap是一个将两个key=value存储为对的对象。 该HashMap允许不同步的空值和空键,并且不保证映射的顺序。

["key","value"] = ["java","mkyong.com"]

1. HashMap Basic

1.1添加项目

Map map = new HashMap<String, String>();
	map.put("PostgreSQL", "Free Open Source Enterprise Database");

1.2取得物品

map.get("PostgreSQL"); // output : Free Open Source Enterprise Database

1.3更新项目

map.put("PostgreSQL", "Still the best!");
	map.get("PostgreSQL"); // output : Still the best!

	// @Since 1.8
	map.replace("PostgreSQL", "Still the best! 2");
	map.get("PostgreSQL"); // output : Still the best! 2

1.4移除物品

map.remove("PostgreSQL");
	map.get("PostgreSQL"); // output : null

1.5删除所有内容

map.clear();

1.6取得尺寸

map.size();

2.循环HashMap

有3种方法来循环或迭代HashMap

2.1如果可能,请始终使用Java 8 forEach ,简单而美观。

Map<String, String> map = new HashMap<>();
    map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

2.2正常的循环。

Map<String, String> map = new HashMap<>();
	
	for (Map.Entry<String, String> entry : map.entrySet()) {
		System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
	}

2.3迭代器,经典。

Map<String, String> map = new HashMap<>();
       
	Iterator iter = map.entrySet().iterator();
	while (iter.hasNext()) {
		Map.Entry entry = (Map.Entry) iter.next();
		System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
	}

3. Collections.synchronizedMap

3.1此HashMap是不同步的,如果多个线程同时访问HashMap ,它将使值混乱。 要在多线程环境中使用HashMap ,请尝试Collections.synchronizedMap(new HashMap<>())创建一个同步映射。

HashMapSynchronized.java
package com.mkyong;

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

public class HashMapSynchronized {

    public static void main(String[] args) {

		// this map is synchronized
        Map<String, Integer> map = Collections.synchronizedMap(new HashMap<>());
		
        map.put("web", 1024);
        map.put("backend", 2048);

        map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

    }

}

4. HashMap

一个完整的例子,仅供参考。

HashMapExample.java
package com.mkyong;

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

public class HashMapExample {

    public static void main(String[] args) {

        Map<String, String> map = new HashMap<>();
        map.put("PostgreSQL", "Free Open Source Enterprise Database");
        map.put("DB2", "Enterprise Database , It's expensive");
        map.put("Oracle", "Enterprise Database , It's expensive");
        map.put("MySQL", "Free Open SourceDatabase (no more, try MariaDB)");

        // Get
        System.out.println(map.get("PostgreSQL")); // Free Open Source Enterprise Database

        // Update
        map.put("PostgreSQL", "Still the best!");
        System.out.println(map.get("PostgreSQL")); // Still the best!

        // @Since 1.8
        map.replace("PostgreSQL", "Still the best! 2");
        System.out.println(map.get("PostgreSQL")); // Still the best! 2

        // Remove
        map.remove("PostgreSQL");
        System.out.println(map.get("PostgreSQL")); // null

        // Size
        System.out.println(map.size()); // 3

        // loop
        System.out.println("Iterator loop...");
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
        }

        System.out.println("for loop...");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
        }

        // Java 8
        System.out.println("forEach loop...");
        map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

        // clear everything
        map.clear();

		// nothing
        map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

    }

}

输出量

Free Open Source Enterprise Database
Still the best!
Still the best! 2
null
3
Iterator loop...
[Key] : DB2 [Value] : Enterprise Database , It's expensive
[Key] : MySQL [Value] : Free Open SourceDatabase (no more, try MariaDB)
[Key] : Oracle [Value] : Enterprise Database , It's expensive
for loop...
[Key] : DB2 [Value] : Enterprise Database , It's expensive
[Key] : MySQL [Value] : Free Open SourceDatabase (no more, try MariaDB)
[Key] : Oracle [Value] : Enterprise Database , It's expensive
forEach loop...
[Key] : DB2 [Value] : Enterprise Database , It's expensive
[Key] : MySQL [Value] : Free Open SourceDatabase (no more, try MariaDB)
[Key] : Oracle [Value] : Enterprise Database , It's expensive

参考文献

翻译自: https://mkyong.com/java/how-to-use-hashmap-tutorial-java/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值