当前位置:   article > 正文

hashmap的三种遍历方式_hashmap遍历

hashmap遍历
  1. /**
  2. * map集合的遍历方式
  3. */
  4. public static void main(String[] args) {
  5. HashMap<String, String> map = new HashMap<>();
  6. map.put("1","q");
  7. map.put("8","q2");
  8. map.put("2","q");
  9. map.put("3","q");
  10. map.put("8","q1");
  11. map.put("4","q");
  12. map.put("5","q");
  13. map.put("8","q3");
  14. //遍历一:获取map集合中的每一对键值对,分别获取key和value
  15. Set<Map.Entry<String, String>> entries = map.entrySet();
  16. for (Map.Entry<String, String> entry : entries) {
  17. System.out.println("key:" + entry.getKey() + " , value:" + entry.getValue());
  18. }
  19. System.out.println("====================================");
  20. //遍历二:获取所有的key,遍历key,获取出value
  21. Set<String> keySet = map.keySet();
  22. for (String key : keySet) {
  23. System.out.println("key:" + key + " , value:" + map.get(key));
  24. }
  25. System.out.println("====================================");
  26. //遍历三;迭代器的方式
  27. Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
  28. while(iterator.hasNext()){
  29. Map.Entry<String, String> next = iterator.next();
  30. System.out.println("key:" + next.getKey() + " , value:" + next.getValue());
  31. }
  32. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/564628
推荐阅读
相关标签
  

闽ICP备14008679号