通过Map.Entry遍历Map的Java程序


创建一个Map,并以键和值的形式插入元素 -

HashMap <String, String> map = new HashMap <String, String> ();
map.put("1", "A");
map.put("2", "B");
map.put("3", "C");
map.put("4", "D");
map.put("5", "E");
map.put("6", "F");
map.put("7", "G");
map.put("8", "H");
map.put("9", "I");

现在,通过Map.Entry遍历Map。在此,我们分别显示了键和值 -

Set<Map.Entry<String, String>>s = map.entrySet();
Iterator<Map.Entry<String, String>>i = s.iterator();
while (i.hasNext()) {
   Map.Entry<String, String>e = (Map.Entry<String, String>) i.next();
   String key = (String) e.getKey();
   String value = (String) e.getValue();
   System.out.println("Key = "+key + " => Value = "+ value);
}

示例

 实时演示

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class Demo {
   public static void main(String[] args) {
      HashMap<String, String>map = new HashMap<String, String>();
      map.put("1", "A");
      map.put("2", "B");
      map.put("3", "C");
      map.put("4", "D");
      map.put("5", "E");
      map.put("6", "F");
      map.put("7", "G");
      map.put("8", "H");
      map.put("9", "I");
      Set<Map.Entry<String, String>>s = map.entrySet();
      Iterator<Map.Entry<String, String>>i = s.iterator();
      while (i.hasNext()) {
         Map.Entry<String, String>e = (Map.Entry<String, String>) i.next();
         String key = (String) e.getKey();
         String value = (String) e.getValue();
         System.out.println("Key = "+key + " => Value = "+ value);
      }
   }
}

输出

Key = 1 => Value = A
Key = 2 => Value = B
Key = 3 => Value = C
Key = 4 => Value = D
Key = 5 => Value = E
Key = 6 => Value = F
Key = 7 => Value = G
Key = 8 => Value = H
Key = 9 => Value = I

更新时间:2019-07-30

136次浏览

开始您的职业生涯

完成课程以获得认证

开始
广告