HashMap遍历方法

java Map遍历速度最优解

第一种(效率高):

Map map = new HashMap();

Iterator iter = mat.entrySet().iterator();

while(iter.hasNext()){

Map.Entry entry = (Map.Entry)iter.next();

Object key = entry.getKey();

Object val = entry.getValue();
}

第二种(效率低):

Map map = new HashMap();

Iterator iter = mat.entrySet().iterator();

while(iter.hasNext()){

Object key = iter.next();

Object val = map.get(key);
}

HashMap的遍历有两种常用方法:使用keyset及entryset进行遍历,但两者的便利速度有差别,下面请看实例:

public class HashMapTest{

public static void main(String[] args)...{

HashMap hashmap = new HashMap();

for(int i=0;i<1000;i)...{

hashmap.put("i","thanks");
}

long bs = Calendar.getInstance().getTimeInMillis();

Iterator iterator = hashmap.keySet().iterator();

while(iterator.hasNext())...{

System.out.print(hashmap.get()iterator.next());
}

System.out.println();

System.out.println(Calendar.getInstance().getTimeInMillis() - bs);

listHashMap();
}

public static void listHashMap()...{

java.util.HashMap hashmap = new java.util.HashMap();

for (int i = 0;i<1000;i)...{

hashmap.put("i","thanks");
}

long bs = Calendar.getInstance().getTimeInMillis();

java.util.Iterator it = hashmap.entrySet().iterator();

while(it.hasNext())...{

java.util.Map.Entry entry = (java.util.Map.Entry)it.next();

//entry.getKey()返回与此项对应的键

//entry.getValue()返回与此项对应的值

System.out.print(entry.getValue());
}

System.out.println();

System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
}
}

对于keySet其实是遍历了2次一次是转为iterator,一次就从hashmap中取出key所对应的value,而entry只遍历了一次,把key和value都放到了entry中,所以就快了

你可能感兴趣的:(HashMap,遍历)