使用迭代器迴圈遍歷 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)); }
廣告