Discussion on the way of Java HASHMAP traversal

Source: Internet
Author: User

Before JDK8, you can use keyset or entryset to traverse HASHMAP,JDK8 by introducing Map.foreach for traversal. Keyset is actually traversed 2 times, one is to iterator object, and the other is to remove key from the HashMap corresponding value. And EntrySet just iterates over it and puts both the key and the value in the entry, which is more efficient. If it is JDK8, use the Map.foreach method. 1. Basic usage of KeySet and 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 after JDK8, Map.foreach was introduced. Map.foreach essence is still entrysetdefault void ForEach (biconsumer<? Super K,? Super V> action) {Objects.requirenonnul        L (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 are no longer in the map.            throw new Concurrentmodificationexception (ISE);        } action.accept (k, v); }} is more convenient to work with with lambda expressions. 2.1 Traverse mapmap<string using Java8 's FOREACH+LAMBDA expression, integer> items = new hashmap<> (), Items.put ("A", 10); Items.put ("B", +), Items.put ("C", "60"), Items.put ("D", +), Items.put ("E", "a"); 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"); }});

  

Discussion on the way of Java HASHMAP traversal

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.