java 轻量级map,java Map 遍历速度最优解
java Map 遍歷速度最優(yōu)解
第一種:
Map map = new HashMap();
Iterator iter = map.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 = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
效率低,以后盡量少使用!
HashMap的遍歷有兩種常用的方法,那就是使用keyset及entryset來(lái)進(jìn)行遍歷,但兩者的遍歷速度是有差別的,下面請(qǐng)看實(shí)例:
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() 返回與此項(xiàng)對(duì)應(yīng)的鍵
// entry.getValue() 返回與此項(xiàng)對(duì)應(yīng)的值
System.out.print(entry.getValue());
}
System.out.println();
System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
}
}
對(duì)于keySet其實(shí)是遍歷了2次,一次是轉(zhuǎn)為iterator,一次就從hashmap中取出key所對(duì)于的value。而entryset只是遍歷了第一次,他把key和value都放到了entry中,所以就快了。
注:Hashtable的遍歷方法和以上的差不多!
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的java 轻量级map,java Map 遍历速度最优解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java轻功游戏,会轻功又可以飞的游戏(
- 下一篇: 公积金贷款买房流程