Java HashMap 遍曆方式探討

來源:互聯網
上載者:User

標籤:一起   lambda   lstat   ext   get   pre   cep   consumer   current   

JDK8之前,可以使用keySet或者entrySet來遍曆HashMap,JDK8中引入了map.foreach來進行遍曆。keySet其實是遍曆了2次,一次是轉為Iterator對象,另一次是從hashMap中取出key所對應的value。而entrySet只是遍曆了一次就把key和value都放到了entry中,效率更高。如果是JDK8,使用Map.foreach方法。1. keySet和entrySet1.1 基本用法keySet:Map map=new HashMap();Iterator it=map.keySet().iterator();Object key;Object value;while(it.hasNext()){key=it.next();value=map.get(key);System.out.println(key+":"+value);}entrySet:Map map=new HashMap();Iterator it=map.entrySet().iterator();Object key;Object value;while(it.hasNext()){Map.Entry entry = (Map.Entry)it.next();key=entry.getKey();value=entry.getValue();System.out.println(key+"="+value);}2. Map.foreach在JDK8以後,引入了Map.foreach。Map.foreach本質仍然是entrySetdefault void forEach(BiConsumer<? super K, ? super V> action) {        Objects.requireNonNull(action);        for (Map.Entry<K, V> entry : entrySet()) {            K k;            V v;            try {                k = entry.getKey();                v = entry.getValue();            } catch(IllegalStateException ise) {                // this usually means the entry is no longer in the map.                throw new ConcurrentModificationException(ise);            }            action.accept(k, v);        }    }配合lambda運算式一起使用,操作起來更加方便。2.1 使用Java8的foreach+lambda運算式遍曆MapMap<String, Integer> items = new HashMap<>();items.put("A", 10);items.put("B", 20);items.put("C", 30);items.put("D", 40);items.put("E", 50);items.put("F", 60); items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v)); items.forEach((k,v)->{    System.out.println("Item : " + k + " Count : " + v);    if("E".equals(k)){        System.out.println("Hello E");    }});

  

Java HashMap 遍曆方式探討

聯繫我們

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