
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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("\nRoll 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("\nRoll Number: " + key); System.out.println("Name: " + student.get(key)); }
- Related Questions & Answers
- Loop through an ArrayList using an Iterator in Java
- Loop through the Vector elements using an Iterator in Java
- Iterate through a LinkedList using an Iterator in Java
- Iterate through a Collection using an Iterator in Java
- Loop through an array in Java
- Traverse through a HashMap in Java
- How to loop through an array in Java?
- Loop through a Set using Javascript
- Loop through ArrayList in Java
- Loop through the Vector elements using a ListIterator in Java
- How to use Iterator to loop through the Map key set?
- Loop through a hash table using Javascript
- Iterate through the values of HashMap in Java
- How to use for each loop through an array in Java?
- Loop through a Dictionary in Javascript
Advertisements