java遍历hashMap、hashSet、Hashtable

一.遍历HashMap

Map<Integer, String> map = new HashMap<Integer, String>();

方法一:效率高

for(Entry<Integer, String> entry:map.entrySet()){
  System.out.println(entry.getKey()+"="+entry.getValue());
}

方法二:

for (Integer key : map.keySet()) { 
  String value = map.get(key); (这样取value会导致效率低,不建议。)
  System.out.println(value);
}

还可以单独遍历value

for (Integer value : map.values()) { 
  System.out.println("Value = " + value); 
}

方法三:(好处:可以在遍历时调用iterator.remove()来删除entries)

Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
  Map.Entry<Integer, Integer> entry = entries.next();
  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

 

二.遍历HashSet

Set set = new HashSet();

for(Iterator it=set.iterator();it.hasNext();){
  System.out.println(it.next());
}

 

三.遍历Hashtable(同步、线程安全的)

Hashtable table = new Hashtable();

//遍历key
Enumeration e = table.keys();

while( e. hasMoreElements() ){

  System.out.println( e.nextElement() );

}
//遍历value
e = table.elements();

while( e. hasMoreElements() ){

  System.out.println( e.nextElement() );

}

 

posted @ 2016-08-30 11:37  一万年以前  阅读(2868)  评论(0编辑  收藏  举报