使用Java中的迭代器循环遍历HashMap
时间:2022-09-25 02:00:00
迭代器可用于遍历HashMap。如果HashMap有更多的元素,然后hasNext()方法返回true,否则返回false。next()方法返回HashMap如果下一个关键元素没有下一个元素,则抛出异常NoSuchElementException。
演示程序的程序如下。
示例importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map;
publicclassDemo{
publicstaticvoidmain(String[]args){
Mapstudent=newHashMap();
student.put("101","Harry");
student.put("102","Amy");
student.put("103","John");
student.put("104","Susan");
student.put("105","James");
Iteratori=student.keySet().iterator();
while(i.hasNext()){
Stringkey=(String)i.next();
System.out.println("\nRollNumber:" key);
System.out.println("Name:" student.get(key));
}
}
}
输出结果
上述程序的输出如下-RollNumber:101
Name:Harry
RollNumber:102
Name:Amy
RollNumber:103
Name:John
RollNumber:104
Name:Susan
RollNumber:105
Name:James
现在让我们了解以上程序。
创建HashMap,并使用HashMap.put()添加条目HashMap。然后,使用Iterator显示接口的迭代器HashMap条目,即键和值。演示此代码片段如下Mapstudent=newHashMap();
student.put("101","Harry");
student.put("102","Amy");
student.put("103","John");
student.put("104","Susan");
student.put("105","James");
Iteratori=student.keySet().iterator();
while(i.hasNext()){
Stringkey=(String)i.next();
System.out.println("\nRollNumber:" key);
System.out.println("Name:" student.get(key));
}