java中遍曆Map幾種方法

來源:互聯網
上載者:User

標籤:16px   運算式   原來   說明   元素   支援   value   效能   ati   

  java中的map遍曆有多種方法,從最早的Iterator,到java5支援的foreach,再到java8 Lambda,讓我們一起來看下具體的用法以及各自的優缺點。

  先初始化一個map:

public class TestMap {  public static Map<Integer, Integer> map = new HashMap<Integer, Integer>();}

keySet values

  如果只需要map的key或者value,用map的keySet或values方法無疑是最方便的

// KeySet 擷取key  public void testKeySet() {    for (Integer key : map.keySet()) {      System.out.println(key);    }  }  // values 擷取value  public void testValues() {    for (Integer value : map.values()) {      System.out.println(value);    }  }

keySet get(key)

  如果需要同時擷取key和value,可以先擷取key,然後再通過map的get(key)擷取value。(需要說明的是,該方法不是最優選擇,一般不推薦使用)

 // keySet get(key) 擷取key and value  public void testKeySetAndGetKey() {    for (Integer key : map.keySet()) {      System.out.println(key + ":" + map.get(key));    }  }

entrySet

  通過對map entrySet的遍曆,也可以同時拿到key和value,一般情況下,效能上要優於上一種,這一種也是最常用的遍曆方法

 // entrySet 擷取key and value  public void testEntry() {    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {      System.out.println(entry.getKey() + ":" + entry.getValue());    }  }

Iterator

  對於上面的幾種foreach都可以用Iterator代替,其實foreach在java5中才被支援,foreach的寫法看起來更簡潔,但Iterator也有其優勢:在用foreach遍曆map時,如果改變其大小,會報錯;但如果只是刪除元素,可以使用Iterator的remove方法刪除元素。

// Iterator entrySet 擷取key and value  public void testIterator() {    Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();    while (it.hasNext()) {      Map.Entry<Integer, Integer> entry = it.next();      System.out.println(entry.getKey() + ":" + entry.getValue());      // it.remove(); 刪除元素    }  }

Lambda

  java8提供了Lambda運算式支援,文法看起來更簡潔,可以同時拿到key和value,不過,經測試,效能低於entrySet,所以更推薦用entrySet的方式

  // Lambda 擷取key and value  public void testLambda() {    map.forEach((key, value) -> {      System.out.println(key + ":" + value);    });  }

總結

  如果只是擷取key,或者value,推薦使用keySet或者values方式

  如果同時需要key和value推薦使用entrySet

  如果需要在遍曆過程中刪除元素推薦使用Iterator

  如果需要在遍曆過程中增加元素,可以建立一個臨時map存放新增的元素,等遍曆完畢,再把臨時map放到原來的map中

 

java中遍曆Map幾種方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.