JAVA遍历MAP集合的四种方式

Map 集合的遍历与 List 和 Set 集合不同。Map 有两组值,因此遍历时可以只遍历值的集合,也可以只遍历键的集合,也可以同时遍历。Map 以及实现 Map 的接口类(如 HashMap、TreeMap、LinkedHashMap、Hashtable 等)都可以用以下几种方式遍历。

1)在 for 循环中使用 entries 实现 Map 的遍历(最常见和最常用的)。

  1. public static void main(String[] args) {
  2. Map<String, String> map = new HashMap<String, String>();
  3. map.put("Java入门教程", "http://c.biancheng.net/java/");
  4. map.put("C语言入门教程", "http://c.biancheng.net/c/");
  5. for (Map.Entry<String, String> entry : map.entrySet()) {
  6. String mapKey = entry.getKey();
  7. String mapValue = entry.getValue();
  8. System.out.println(mapKey + ":" + mapValue);
  9. }
  10. }

2)使用 for-each 循环遍历 key 或者 values,一般适用于只需要 Map 中的 key 或者 value 时使用。性能上比 entrySet 较好。

  1. Map<String, String> map = new HashMap<String, String>();
  2. map.put("Java入门教程", "http://c.biancheng.net/java/");
  3. map.put("C语言入门教程", "http://c.biancheng.net/c/");
  4. // 打印键集合
  5. for (String key : map.keySet()) {
  6. System.out.println(key);
  7. }
  8. // 打印值集合
  9. for (String value : map.values()) {
  10. System.out.println(value);
  11. }

3)使用迭代器(Iterator)遍历

  1. Map<String, String> map = new HashMap<String, String>();
  2. map.put("Java入门教程", "http://c.biancheng.net/java/");
  3. map.put("C语言入门教程", "http://c.biancheng.net/c/");
  4. Iterator<Entry<String, String>> entries = map.entrySet().iterator();
  5. while (entries.hasNext()) {
  6. Entry<String, String> entry = entries.next();
  7. String key = entry.getKey();
  8. String value = entry.getValue();
  9. System.out.println(key + ":" + value);
  10. }

4)通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作。

  1. for(String key : map.keySet()){
  2. String value = map.get(key);
  3. System.out.println(key+":"+value);
  4. }
点赞 ( 0 )

0 条评论

发表评论

人生在世,错别字在所难免,无需纠正。

插入图片
s
返回顶部