java遍历hashMap、hashSet、Hashtable

时间:2021-12-21 15:41:03

一.遍历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() );

}