通過Map.values()遍歷所有的value,不能遍歷key
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
通過獲取HashMap中所有的key按照key來遍歷
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
通過Map.entrySet使用iterator遍歷key和value
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
通過Map.entrySet遍歷key和value
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