HashMap的遍历共有两种:
1.利用entrySet 键值对映射:
Map map = new HashMap();
Iterator it = map.entrySet().iterator();
while(it.hashNext()){
Map.Entry s = (Map.Entry)it.next();
System.out.println(s.getKey());
System.out.println(s.getValue());
}
2.利用keySet:
Map map = new HashMap();
Iterator it = map.keySet().iterator();
while(it.hasNext()){
Object key = it.next();
System.out.println(key);
System.out.println(map.get(key));
}
LinkedHashMap的遍历,保证读取数据的顺序和put的顺序一致:
/**
* LinkedHashMap倒序
* @author zzw
*
*/
public class LinkedHashMapSort {
public static void main(String[] args) {
LinkedHashMap <String,String > linkedhashmap = new LinkedHashMap<String,String>();
linkedhashmap.put("1","a");
linkedhashmap.put("2","b");
linkedhashmap.put("3","c");
linkedhashmap.put("4","d");
ListIterator<Map.Entry<String,String>> i=new ArrayList<Map.Entry<String,String>>
(linkedhashmap.entrySet()).listIterator(linkedhashmap.size());
while(i.hasPrevious()) {
Map.Entry<String, String> entry=i.previous();
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}