原文: https://beginnersbook.com/2013/12/how-to-loop-hashmap-in-java/
在本教程中,我们将学习如何使用以下方法循环HashMap:
for循环while循环 + 迭代器
示例:
在下面的示例中,我们使用两种方法(for循环和while循环)迭代HashMap。在while循环中,我们使用了迭代器。
package beginnersbook.com;import java.util.HashMap;import java.util.Map;import java.util.Iterator;public class Details{public static void main(String [] args){HashMap<Integer, String> hmap = new HashMap<Integer, String>();//Adding elements to HashMaphmap.put(11, "AB");hmap.put(2, "CD");hmap.put(33, "EF");hmap.put(9, "GH");hmap.put(3, "IJ");//FOR LOOPSystem.out.println("For Loop:");for (Map.Entry me : hmap.entrySet()) {System.out.println("Key: "+me.getKey() + " & Value: " + me.getValue());}//WHILE LOOP & ITERATORSystem.out.println("While Loop:");Iterator iterator = hmap.entrySet().iterator();while (iterator.hasNext()) {Map.Entry me2 = (Map.Entry) iterator.next();System.out.println("Key: "+me2.getKey() + " & Value: " + me2.getValue());}}}
输出:
For Loop:Key: 2 & Value: CDKey: 3 & Value: IJKey: 33 & Value: EFKey: 9 & Value: GHKey: 11 & Value: ABWhile Loop:Key: 2 & Value: CDKey: 3 & Value: IJKey: 33 & Value: EFKey: 9 & Value: GHKey: 11 & Value: AB
