hashmap中有4种遍历的方法,以下分别介绍它们的使用
1. Iterator迭代遍历
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapIteratorExample {
public static void main(String[] args) {
//通过Map.entrySet使用iterator遍历key和value:
Map<String, String> map = new HashMap<String, String>();
map.put("baidu","百度");
map.put("taobao","淘宝");
map.put("yxjc123","易学教程");
map.put("sohu","搜狐");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + ", value= " + entry.getValue());
}
}
}
2. map循环遍历
import java.util.HashMap;
import java.util.Map;
public class HashMapEntryExample {
public static void main(String[] args) {
//通过Map.entrySet遍历key和value,尤其是容量大时
Map<String, String> map = new HashMap<String, String>();
map.put("baidu","百度");
map.put("taobao","淘宝");
map.put("yxjc123","易学教程");
map.put("sohu","搜狐");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " , value= " + entry.getValue());
}
}
}
3. for循环遍历第一种方法import java.util.HashMap;
import java.util.Map;
public class HashMapForExample1 {
public static void main(String[] args) {
//通过Map.keySet遍历key和value,普遍使用,二次取值
Map<String, String> map = new HashMap<String, String>();
map.put("baidu","百度");
map.put("taobao","淘宝");
map.put("yxjc123","易学教程");
map.put("sohu","搜狐");
for (String key : map.keySet()) {
System.out.println("key= "+ key + " , value= " + map.get(key));
}
}
}
4. for循环遍历第二种方法
import java.util.HashMap;
import java.util.Map;
public class HashMapForExample2{
public static void main(String[] args) {
//通过Map.values()遍历所有的value,但不能遍历key
Map<String, String> map = new HashMap<String, String>();
map.put("baidu","百度");
map.put("taobao","淘宝");
map.put("yxjc123","易学教程");
map.put("sohu","搜狐");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}
}