利用Map.Entry和for each对Hashmap进行输出

来源:互联网 发布:怎么做淘宝店铺模板 编辑:程序博客网 时间:2024/06/14 12:00

1、利用Map.Entry

import java.util.*;
public class hashmap {
 public static void main(String args[])
 {
  HashMap<Integer, String> hashmap= new HashMap<Integer, String>();
  hashmap.put(1, "一");
  hashmap.put(2, "二");
  hashmap.put(3, "三");
  hashmap.put(4, "四");
  Set<Map.Entry<Integer, String>> allset = hashmap.entrySet();
  Iterator<Map.Entry<Integer, String>> a = allset.iterator();
  while(a.hasNext())
  {
   Map.Entry<Integer, String> me = a.next();//进行key和value分离
   System.out.println(me.getKey() + "--->" + me.getKey());//输出关键字和内容
  
 }
}

2、用foreach对Hashmap进行输出:

import java.util.*;
public class hashmap {
 public static void main(String args[])
 {
  HashMap<Integer, String> hashmap= new HashMap<Integer, String>();
  hashmap.put(1, "一");
  hashmap.put(2, "二");
  hashmap.put(3, "三");
  hashmap.put(4, "四");
  for(Map.Entry<Integer, String> me: hashmap.entrySet()) 
  {//me是存放hashmap中取出的内容,并用Map.Entry<Integer, String> 指定其泛型
   System.out.println(me.getKey() + "-->" + me.getValue());
  }
 }
}

0 0
原创粉丝点击