遍历HashMap
如何遍历HashMap?
Key的迭代器
Key的for(这里的for是for的另一种用法,普通for无法得出结果,因为set是无序的)
对整个entry的迭代器,当然也有for的方法,同理就不列举了
import java.util.*;
import java.util.Map.Entry;
import javax.swing.text.html.parser.Entity;
public class TestMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
Set<String> keys = map.keySet();
System.out.println("使用迭代器勉励");
Iterator<String> keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
String value = map.get(key);
System.out.println(key + "," + value);
}
System.out.println("使用增强for遍历");
for (String key : keys) {
String value = map.get(key);
System.out.println(key + "," + value);
}
Set<Map.Entry<String, String>> entrys = map.entrySet();
Iterator<Map.Entry<String,String>> it = entrys.iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println(entry.getKey()+","+entry.getValue());
}
}
}
结果展示: