Java中遍历HashMap的方法
要遍历HashMap,请使用Iterator。HashMap类使用哈希表来实现Map接口。这允许基本操作(如get()和put())的执行时间保持恒定,即使对于较大的集合也是如此。
以下是遍历HashMap的代码-
示例
import java.util.*;
public class Main {
public static void main(String args[]) {
HashMap hashMap = new HashMap();
hashMap.put("John", new Integer(10000));
hashMap.put("Tim", new Integer(25000));
hashMap.put("Adam", new Integer(15000));
hashMap.put("Katie", new Integer(30000));
hashMap.put("Jacob", new Integer(45000));
hashMap.put("Steve", new Integer(23000));
hashMap.put("Nathan", new Integer(25000));
hashMap.put("Amy", new Integer(27000));
Set set = hashMap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry map = (Map.Entry)iterator.next();
System.out.print(map.getKey() + ": ");
System.out.println(map.getValue());
}
System.out.println();
System.out.println("IdentintyHashMap的大小: "+hashMap.size());
int bonus = ((Integer)hashMap.get("Amy")).intValue();
hashMap.put("Amy", new Integer(bonus + 5000));
System.out.println("艾米扣除奖金后的薪水 = " + hashMap.get("Amy"));
int deductions = ((Integer)hashMap.get("Steve")).intValue();
hashMap.put("Steve", new Integer(deductions - 3000));
System.out.println("史蒂夫扣除奖金后的薪水 = " + hashMap.get("Steve"));
}
}输出结果
Adam: 15000 Nathan: 25000 Katie: 30000 Steve: 23000 John: 10000 Tim: 25000 Amy: 27000 Jacob: 45000 IdentintyHashMap的大小: 8 艾米扣除奖金后的薪水 = 32000 史蒂夫扣除奖金后的薪水 = 20000
您还可以使用for-each循环遍历HashMap。这里需要keySet()和values()方法来分别显示键和值。现在让我们看另一个示例,其中我们将使用for-each遍历HashMap-
示例
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> students = new HashMap<String, String>();
students.put("John", "Maths");
students.put("Tim", "Political Science");
students.put("Steve", "English");
students.put("Nathan", "Science");
for (String s : students.keySet()) {
System.out.println("key= " + s + ", value= " + students.get(s));
}
}
}输出结果
key= Nathan, value= Science key= Steve, value= English key= John, value= Maths key= Tim, value= Political Science