hashmap的四种遍历方法

  1. package exam;


  2. import java.util.Collection;
  3. import java.util.HashMap;
  4. import java.util.Iterator;
  5. import java.util.Map;
  6. import java.util.Map.Entry;
  7. import java.util.Set;


  8. public class MapTest {
  9. public static void main(String[] args) {
  10. HashMap<String, Integer> map = new HashMap<String,Integer>(20);
  11. map.put("a", 1);
  12. map.put(null, 2);
  13. map.put("h", null);
  14. // Entry_bianli(map);
  15. // Key_value(map);
  16. // FenBieBianLi(map);
  17. fanXing(map);
  18. }
  19. //使用map.entrySet().iterator进行遍历
  20. static public void Entry_bianli(Map map)
  21. {
  22. Iterator<Map.Entry<String, Integer>> ite = map.entrySet().iterator();
  23. while(ite.hasNext())
  24. {
  25. Map.Entry<String, Integer> entry = ite.next();
  26. System.out.println(entry.getKey()+" "+entry.getValue());
  27. }
  28. }
  29. //分别遍历出map的key和value
  30. static public void Key_value(Map map)
  31. {
  32. Set keyset = map.keySet();
  33. Iterator ite = keyset.iterator();
  34. while(ite.hasNext())
  35. {
  36. Object key = ite.next();
  37. System.out.println("key = "+key+" value = "+map.get(key));
  38. }
  39. }
  40. //获取map的keySet,foreach获取key,然后通过map.get(key)找到value
  41. static public void FenBieBianLi(Map map)
  42. {
  43. Set key = map.keySet();
  44. Collection value = map.values();
  45. for(Object ob : key)
  46. {
  47. System.out.println(ob);
  48. }
  49. for(Object ob : value)
  50. {
  51. System.out.println(ob);
  52. }
  53. }
  54. //获取map.entrySet(注意返回的是类型为Entry的Set),之后foreach遍历set,然后对每一项使用entry的getKey
  55. //和getValue方法.
  56. static public void fanXing(Map map)
  57. {
  58. Set<Entry<String,Integer>> set = map.entrySet();
  59. for(Entry<String,Integer> entry:set)
  60. {
  61. System.out.println(entry.getKey()+" "+entry.getValue());
  62. }
  63. }
  64. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值