Preface
There are many ways to traverse Map in Java. In this article, let’s take a look at the two methods of reading Map in Java and the comparison of these two methods.
1. traversal 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(); } 2. Traversing Map method B
Map map = new HashMap(); Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); Object val = map.get(key); } 3. Analysis traversal method
Method A: Read Map.Entry once in the traversal, and then directly obtain the value.
Method B: Based on keySet, iterates through first, and then reads information from the Map.
4. Performance testing
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("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()-startTime) + "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()-startTime) + "milli seconds"); } }Test results:
It can be seen that 1000,000 data are stored in the Map and traversed in this data set. The performance difference is nearly 1 times the difference in efficiency.
5. Summary
Okay, the above is all about this article. You can see that the efficiency of car method A is generally higher. Generally, it is recommended to use method A. I hope that the content of this article will be of some help to everyone’s study or work.