在Java HashMap中,我们可以遍历其keys , values和key / value映射。
示例1:使用forEach循环遍历HashMap
import java.util.HashMap;
import java.util.Map.Entry;
class Main {
public static void main(String[] args) {
// Creating a HashMap
HashMap languages = new HashMap<>();
languages.put("Java", "Enterprise");
languages.put("Python", "ML/AI");
languages.put("JavaScript", "Frontend");
System.out.println("HashMap: " + languages);
// iterating through key/value mappings
System.out.print("Entries: ");
for(Entry entry: languages.entrySet()) {
System.out.print(entry);
System.out.print(", ");
}
// iterating through keys
System.out.print("\nKeys: ");
for(String key: languages.keySet()) {
System.out.print(key);
System.out.print(", ");
}
// iterating through values
System.out.print("\nValues: ");
for(String value: languages.values()) {
System.out.print(value);
System.out.print(", ");
}
}
}
输出
HashMap: {Java=Enterprise, JavaScript=Frontend, Python=ML/AI}
Entries: Java=Enterprise, JavaScript=Frontend, Python=ML/AI,
Keys: Java, JavaScript, Python,
Values: Enterprise, Frontend, ML/AI,
在上面的示例中,我们创建了一个名为language的哈希表。在这里,我们使用了forEach
循环来遍历哈希映射的元素。
注意,我们独立地遍历key , values和key / value映射。
- language.entrySet()-返回所有条目的设置视图
- language.keySet()-返回所有键的设置视图
- language.values()-返回所有值的设置视图
注意 :我们使用了Map.Entry
类。嵌套类返回地图视图。
示例2:使用iterator()遍历HashMap
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
class Main {
public static void main(String[] args) {
// create a HashMap
HashMap languages = new HashMap<>();
languages.put("Java", "Enterprise");
languages.put("Python", "ML/AI");
languages.put("JavaScript", "Frontend");
System.out.println("HashMap: " + languages);
// create an object of Iterator
Iterator> iterate1 = languages.entrySet().iterator();
// iterate through key/value mappings
System.out.print("Entries: ");
while(iterate1.hasNext()) {
System.out.print(iterate1.next());
System.out.print(", ");
}
// iterate through keys
Iterator iterate2 = languages.keySet().iterator();
System.out.print("\nKeys: ");
while(iterate2.hasNext()) {
System.out.print(iterate2.next());
System.out.print(", ");
}
// iterate through values
Iterator iterate3 = languages.values().iterator();
System.out.print("\nValues: ");
while(iterate3.hasNext()) {
System.out.print(iterate3.next());
System.out.print(", ");
}
}
}
输出
HashMap: {Java=Enterprise, JavaScript=Frontend, Python=ML/AI}
Entries: Java=Enterprise, JavaScript=Frontend, Python=ML/AI,
Keys: Java, JavaScript, Python,
Values: Enterprise, Frontend, ML/AI,
在上面的示例中,我们遍历哈希映射的键,值和键/值映射。我们使用了iterator()
方法来迭代哈希图。这里,
- hasNext() -如果哈希图中存在下一个元素,则返回
true
- next() -返回哈希图的下一个元素
注意 :我们还可以使用HashMap forEach()方法来迭代哈希图。