Java –如何迭代HashMap

在Java中,有3种方法来循环或迭代HashMap

1.如果可能,请始终使用Java 8 forEach

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

entrySet() for循环正常

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

3.经典迭代器。

Map 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());
	}

HashMap示例

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

HashMapExample.java
package com.mkyong.calculator;

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

public class HashMapExample {

    public static void main(String[] args) {

        Map map = new HashMap<>();
        map.put("web", 1024);
        map.put("database", 2048);
        map.put("static", 5120);

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

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

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

    }

}

输出量

Java 8 forEach loop
[Key] : database [Value] : 2048
[Key] : static [Value] : 5120
[Key] : web [Value] : 1024
for entrySet()
[Key] : database [Value] : 2048
[Key] : static [Value] : 5120
[Key] : web [Value] : 1024
Iterator
[Key] : database [Value] : 2048
[Key] : static [Value] : 5120
[Key] : web [Value] : 1024

参考文献

  • Java HashMap JavaDocs
  • Java HashMap示例

翻译自: https://mkyong.com/java/java-how-to-iterate-a-hashmap/

你可能感兴趣的:(Java –如何迭代HashMap)