HashMap遍历 key value

来源:互联网 发布:四维星设计软件 编辑:程序博客网 时间:2024/06/05 03:54
  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
HashMap遍历的两种方式: 第一种:
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); }
效率低比第一种要低,不推荐使用!
public class HashMapTest {
public static void main(String[] args) {
HashMap hashmap = new HashMap();
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.out.println(Calendar.getInstance().getTimeInMillis() - bs);
listHashMap();
}
public static void listHashMap(){
java.util.HashMap hashmap = new java.util.HashMap();
for (int i = 0; i < 1000; i++ ){
hashmap.put(i, "thanks");
}
long bs = Calendar.getInstance().getTimeInMillis();
java.util.Iterator it = hashmap.entrySet().iterator();
while (it.hasNext()){
java.util.Map.Entry entry = (java.util.Map.Entry) it.next();// entry.getKey() 返回与此项对应的键
// entry.getValue() 返回与此项对应的值
System.out.print(entry.getValue());
}
System.out.println();
System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
} }
0 0
原创粉丝点击