There are two ways for HashMap traversal. Entryset() is recommended
•
Java
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(); }
Map map = new HashMap(); Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); Object val = map.get(key); }
import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; public class HashMapTest { public static void main(String[] args) { keySet(); entrySet(); } public static void keySet() { HashMap<Integer,String> hashmap = new HashMap<Integer,String>(); for (int i = 0; i < 1000; i++) { hashmap.put(i,"thanks"); } long bs = Calendar.getInstance().getTimeInMillis(); Iterator iterator = hashmap.keySet().iterator(); while (iterator.hasNext()) { System.out.print(hashmap.get(iterator.next())); } System.out.println(); System.err.println(Calendar.getInstance().getTimeInMillis() - bs); } public static void entrySet() { HashMap<Integer,"thanks"); } long bs = Calendar.getInstance().getTimeInMillis(); Iterator it = hashmap.entrySet().iterator(); while (it.hasNext()) { Entry entry = (Entry) it.next(); // entry.getKey() 返回与此项对应的键 // entry.getValue() 返回与此项对应的值 System.out.print(entry.getValue()); } System.out.println(); System.err.println(Calendar.getInstance().getTimeInMillis() - bs); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码