Objective
There are many ways to traverse a map in Java. In this article, let's take a look at the two methods of Java reading map and the comparison between the two methods.
First, traversing the map method a
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 ();
Second, traverse map method B
Map map = new HashMap ();
Iterator iter = Map.keyset (). iterator ();
while (Iter.hasnext ()) {
Object key = Iter.next ();
Object val = map.get (key);
Three, analysis traversal method
Method A: A value that is read once in the traversal and Map.Entry then obtained directly.
Method B: Based on keyset, the first traversal, then read the information from the map.
Four, performance test
Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Map;
Import Org.junit.BeforeClass;
Import Org.junit.Test;
public class Maploopa {private static Map<integer, string> infos = new Hashmap<integer, string> ();
@BeforeClass public static void SetUp () {for (int i=0; i<1000000; i++) {infos.put (i, "test information" + i);
} System.out.println ("The setUp is done."); @Test public void Testmaploopa () {iterator<map.entry<integer, string>> iterator = Infos.entryset ().
Iterator ();
Long starttime = System.currenttimemillis ();
while (Iterator.hasnext ()) {Map.entry<integer, string> Entry = Iterator.next ();
int key = Entry.getkey ();
String val = Entry.getvalue (); } System.out.println ("A solution takes in looping Map with 1000000 entries:" + (System.currenttimemillis ()-startt
IME) + "milli seconds"); @Test public void Testmaploopb () {iterator<integer> iterator = infos.keYset (). iterator ();
Long starttime = System.currenttimemillis ();
while (Iterator.hasnext ()) {int key = Iterator.next ();
String val = infos.get (key); } System.out.println ("B solution takes in looping Map with 1000000 entries:" + (System.currenttimemillis ()-startt
IME) + "milli seconds"); }
}
Test results:
This shows that 1 million data is stored in the map and traversed in this data collection. Performance differences that are nearly 1 time times more efficient.
V. Summary
Well, the above is the entire content of this article, you can take a car the efficiency of the method A is generally higher. Generally recommended you use method A. I hope the content of this article for everyone's study or work can bring certain help.