码迷,mamicode.com
首页 > 其他好文 > 详细

HashMap的两种遍历方式

时间:2018-07-08 00:00:02      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:方法   lin   性能   hashmap   迭代器   循环   index   keyset   key值   

首先定义一个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循环迭代是一种,使用迭代器是一种。

   

 

HashMap的两种遍历方式

标签:方法   lin   性能   hashmap   迭代器   循环   index   keyset   key值   

原文地址:https://www.cnblogs.com/jdbc2nju/p/9278805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!