- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Loop through a HashMap using an Iterator in Java
An Iterator can be used to loop through a HashMap. The method hasNext( ) returns true if there are more elements in HashMap and false otherwise. The method next( ) returns the next key element in the HashMap and throws the exception NoSuchElementException if there is no next element.
A program that demonstrates this is given as follows.
Example
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)); } } }
Output
The output of the above program is as follows −
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
Now let us understand the above program.
The HashMap is created and HashMap.put() is used to add the entries to the HashMap. Then the HashMap entries i.e. the keys and the values are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows
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)); }
Advertisements