What are different ways of iterating over keys, values and entry in Map?
Answer:
Create and put key-value pairs in HashMap
Iterate over keys :-
hashMap.keySet().iterator() method returns iterator to iterate over keys in HashMap.
/*OUTPUT
21
41
11
31
*/
Iterate over values :-
hashMap.values().iterator() method returns iterator to iterate over keys in HashMap.
/*OUTPUT
IT
EEE
CSS
ECE
*/
Iterate over Entry-
hashMap.entrySet().iterator() method returns iterator to iterate over keys in HashMap.
/*OUTPUT
21=IT
41=EEE
11=CSS
31=ECE
*/
Create and put key-value pairs in HashMap
package com.tutorial4u;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
Map hashMap = new HashMap();
hashMap.put(11, "CSS");
hashMap.put(21, "IT");
hashMap.put(31, "ECE");
hashMap.put(41, "EEE");
}
}
|
hashMap.keySet().iterator() method returns iterator to iterate over keys in HashMap.
Iterator keyIterator =hashMap.keySet().iterator();
while(keyIterator.hasNext()){
System.out.println(keyIterator.next());
}
|
/*OUTPUT
21
41
11
31
Iterate over values :-
hashMap.values().iterator() method returns iterator to iterate over keys in HashMap.
Iterator valueIterator=hashMap.values().iterator();
while(valueIterator.hasNext()){
System.out.println(valueIterator.next());
}
|
/*OUTPUT
IT
EEE
CSS
ECE
Iterate over Entry-
hashMap.entrySet().iterator() method returns iterator to iterate over keys in HashMap.
Iterator entryIterator=hashMap.entrySet().iterator();
while(entryIterator.hasNext()){
System.out.println(entryIterator.next());
}
|
21=IT
41=EEE
11=CSS
31=ECE
No comments:
Post a Comment