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());
}
}
}
本文介绍了两种遍历HashMap的方法:使用entrySet键值对映射及使用keySet。此外,还展示了如何按插入顺序遍历LinkedHashMap,并提供了一个具体的Java实现示例。

885

被折叠的 条评论
为什么被折叠?



