zoukankan      html  css  js  c++  java
  • HashMap的两种遍历方式

    首先定义一个HashMap:

    Map<String, String> map = new HashMap<String, String>();

    两种遍历方式分别为使用keySet和entrySet

    keySet存放的只是HashMap的key值,entrySet存放的是HashMap的key-value整体

    keySet的性能不如entrySet

    方法一:

    for (String key : map.keySet()) {
    String value = map.get(keys);

    }

    或者:

    Set<String> keySet = map.keySet();
    Iterator<String> it = keySet.iterator();
    while (it.hasNext()) {
        String key = it.next();
        String value = map.get(key)
    }

    方法二:

    for (Entry<String, String> entry : map.entrySet()) {
         String keys = entry.getKey();
         String values = entry.getValue();

    }

    或者:

    Set<Map.Entry<String, String>> entrySet = map.entrySet();

    Iterator<Map.Entry<String, String>> it = entrySet.iterator();

    while (it.hasNext()) {

        Map.Entry(String, String) entry = it.next();

        String key = entry.getKey();

        String value = entry.getValue();

    }

    当然你也可以说成四种方法。

    或者同样是两种方法,使用for循环迭代是一种,使用迭代器是一种。

       

  • 相关阅读:
    第01组 Beta冲刺(5-5)
    第01组 Beta冲刺(4-5)
    第01组 Beta冲刺(3-5)
    第01组 Beta冲刺(2-5)
    第01组 Beta冲刺(1-5)
    软工实践个人总结
    第03组 每周小结 (3/3)
    第03组 每周小结 (2/3)
    第03组 每周小结 (1/3)
    第03组 Beta冲刺 总结
  • 原文地址:https://www.cnblogs.com/jdbc2nju/p/9278805.html
Copyright © 2011-2022 走看看