使用迭代器循环遍历 Java 中的 HashMap
迭代器可用于循环遍历 HashMap。如果 HashMap 中有更多元素,方法 hasNext( ) 会返回 true,否则返回 false。方法 next( ) 会返回 HashMap 中下一个键元素,如果没有下一个元素,则抛出 NoSuchElementException 异常。
下面给出了一个对此进行演示的程序。
示例
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Demo {
public static void main(String[] args) {
Map student = new HashMap();
student.put("101", "Harry");
student.put("102", "Amy");
student.put("103", "John");
student.put("104", "Susan");
student.put("105", "James");
Iterator i = student.keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
System.out.println("
Roll Number: " + key);
System.out.println("Name: " + student.get(key));
}
}
}输出
上面程序的输出如下 −
Roll Number: 101 Name: Harry Roll Number: 102 Name: Amy Roll Number: 103 Name: John Roll Number: 104 Name: Susan Roll Number: 105 Name: James
现在,让我们来理解一下上面的程序。
创建 HashMap,并使用 HashMap.put() 将条目添加到 HashMap 中。然后使用迭代器显示 HashMap 条目,即键和值,该迭代器使用 Iterator 接口。下面是一个展示此操作的代码片段
Map student = new HashMap();
student.put("101", "Harry");
student.put("102", "Amy");
student.put("103", "John");
student.put("104", "Susan");
student.put("105", "James");
Iterator i = student.keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
System.out.println("
Roll Number: " + key);
System.out.println("Name: " + student.get(key));
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP