Java Map集合遍历的5种方式

通过检索,简单归纳了Map集合的五种遍历方式,根据需求选择。

  1. 获取键值对用ForEach循环

public static void main(String[] args) throws IOException {

    Map map = new HashMap();
    map.put(1, 10);
    map.put(2, 20);

    // Iterating entries using a For Each loop
    for (Map.Entry entry : map.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    }

}
  1. 仅获取键/值

仅需key值或者value值的时候可以选择,不建议通过循环keySet()键集合的方法来遍历整个Map集合,会造成两次遍历,浪费性能。

public static void main(String[] args) throws IOException {

    Map map = new HashMap();
    map.put(1, 10);
    map.put(2, 20);

    // Iterating over keys
    for (Integer key : map.keySet()) {
        System.out.println("Key = " + key);
    }

    // Iterating over values
    for (Integer value : map.values()) {
        System.out.println("Value = " + value);
    }
}
  1. 使用带泛型的迭代器进行遍历

在JDK支持泛型的版本种可以选择

public static void main(String[] args) throws IOException {

    Map map = new HashMap();
    map.put(1, 10);
    map.put(2, 20);

    Iterator> entries = map.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry entry = entries.next();
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    }
}
  1. 使用不带泛型的迭代器进行遍历

在JDK不支持泛型的版本种可以选择

public static void main(String[] args) throws IOException {

    Map map = new HashMap();
    map.put(1, 10);
    map.put(2, 20);

    Iterator entries = map.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry entry = (Map.Entry) entries.next();
        Integer key = (Integer) entry.getKey();
        Integer value = (Integer) entry.getValue();
        System.out.println("Key = " + key + ", Value = " + value);
    }
}
  1. JDK 8 及以后版本 Lambda表达式

public static void main(String[] args) throws IOException {

    Map map = new HashMap();
    map.put(1, 10);
    map.put(2, 20);
    map.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
}

你可能感兴趣的:(java,开发语言,jvm)