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