Java Map遍曆速度最優解

來源:互聯網
上載者:User

第一種:

  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來進行遍曆,但兩者的遍曆速度是有差別的,下面請看執行個體:

  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。而entryset只是遍曆了第一次,他把key和value都放到了entry中,所以就快了。

  注:Hashtable的遍曆方法和以上的差不多!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.