public class TestDemo{
public static void main(String[] args) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("name","Jack");
hashMap.put("sex","boy");
// 通过Map.values()遍历所有的value,不能遍历key
for (String v : hashMap.values()) {
System.out.println("value=" + v);
}
}
}
执行结果如下:
value=boy
value=Jack
public class TestDemo{
public static void main(String[] args) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("name","Jack");
hashMap.put("sex","boy");
// 通过获取HashMap中所有的key按照key来遍历
for (String key : hashMap.keySet()) {
//得到每个key多对用value的值
String value = hashMap.get(key);
System.out.println("key="+ key +"; value="+value);
}
}
}
执行结果如下:
key=sex; value=boy
key=name; value=Jack
public class TestDemo{
public static void main(String[] args) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("name","Jack");
hashMap.put("sex","boy");
// 通过Map.entrySet使用iterator遍历key和value
Iterator<Map.Entry<String, String>> entryIterator =
hashMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<String, String> entry = entryIterator.next();
System.out.println("key=" + entry.getKey() + "; value= " +
entry.getValue());
}
}
}
执行结果如下:
key=sex; value=boy
key=name; value=Jack
public class TestDemo{
public static void main(String[] args) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("name","Jack");
hashMap.put("sex","boy");
// 通过Map.entrySet遍历key和value,[推荐]
for (Map.Entry<String, String> stringEntry : hashMap.entrySet()){
System.out.println("key=" + stringEntry.getKey() + "; value="
+ stringEntry.getValue());
}
}
}
执行结果如下:
key=sex; value=boy
key=name; value=Jack