JAVA 迭代 HashMap

循环HashMap,输出其值。
如果你只想获取 key,可以使用 keySet() 方法,然后可以通过 get(key) 获取对应的 value;如果你只想获取 value,可以使用 values() 方法。
方法一:for-each
import java.util.HashMap;

public class RunoobTest {
public static void main(String[] args) {
// 创建 HashMap 对象 hashMap
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
// 添加键值对
hashMap.put(1, “泰山”);
hashMap.put(2, “华山”);
hashMap.put(3, “嵩山”);
hashMap.put(4, “衡山”);
hashMap.put(5, “恒山”);
// 输出 key 和 value
for (Integer i : Sites.keySet()) {
System.out.println("key: " + i + " value: " + hashMap.get(i));
}
// 返回所有 value 值
for(String value: hashMap.values()) {
// 输出每一个value
System.out.print(value + ", ");
}

}
}
运行结果如下:
key: 1 value: 泰山
key: 2 value: 华山
key: 3 value: 嵩山
key: 4 value: 衡山
key: 5 value: 恒山
泰山, 华山, 嵩山, 衡山, 恒山

方法二:使用迭代器Iterator
import java.util.Iterator;
import java.util.HashMap;

public class RunoobTest {
public static void main(String[] args) {
// 创建 HashMap 对象 hashMap
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
// 添加键值对
hashMap.put(1, “泰山”);
hashMap.put(2, “华山”);
hashMap.put(3, “嵩山”);
hashMap.put(4, “衡山”);
hashMap.put(5, “恒山”);
// 获取迭代器
Iterator<Map.Entry<Integer, String>> entries = hashMap.entrySet().iterator();

while (entries.hasNext()) {
Map.Entry<Integer, String> entry = entries.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
运行结果如下:
key: 1 value: 泰山
key: 2 value: 华山
key: 3 value: 嵩山
key: 4 value: 衡山
key: 5 value: 恒山

猜你喜欢

转载自blog.csdn.net/weixin_46075394/article/details/115242664