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

   

猜你喜欢

转载自www.cnblogs.com/jdbc2nju/p/9278805.html