Best Way to Iterate Any Map
in java
Iterating over Map in java there are basically 4 different ways in
this article we will look each and every one by one with example. Also we will
use Java 8 forEach() method for iterating all the Map interface child class.
1] Iterating using enhanced for loop Example
This is basic and most used technique to iterate the any map implementations
in java.
package com.vr.cls;
import java.util.HashMap;
import java.util.Map;
public class
DifferentIteratingMapDemo {
public static void main(String[] args) {
Map map = new HashMap();
map.put(20, "tiger");
map.put(40, "lion");
map.put(30, "parrot");
map.put(70, "cow");
map.put(50, "deer");
for(Map.Entry
entry : map.entrySet())
{
System.out.println("Key : "+entry.getKey() +" "+
"value : "+entry.getValue());
}
}
}
Output
Key : 50 value : deer
Key : 20 value : tiger
Key : 70 value : cow
Key : 40 value : lion
Key : 30 value : parrot
2] Iterating using Iterator interface over Map.Entry
This is also basic and most used technique to iterate using
Iterator interface over the Map.Entry, using this method benefits is
to we can remove the element while iterating.
package com.vr.cls;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class
DifferentIteratingMapDemo {
public static void main(String[] args) {
Map map = new HashMap ();
map.put(20, "tiger");
map.put(40, "lion");
map.put(30, "parrot");
map.put(70, "cow");
map.put(50, "deer");
IteratoritrEntry = map.entrySet().iterator();
while (itrEntry.hasNext())
{
Entry
entry = itrEntry.next();
System.out.println("Key : "+entry.getKey() +" "+
"value : "+entry.getValue());
}
}
}
3] Iterating using keySet () and values () method
This is very easy and simple method of iterating the element using
keySet() and values() we can iterate the map for any particular requirement.
package com.vr.cls;
import java.util.HashMap;
import java.util.Map;
public class
DifferentIteratingMapDemo {
public static void main(String[] args) {
Map map = new HashMap();
map.put(20, "tiger");
map.put(40, "lion");
map.put(30, "parrot");
map.put(70, "cow");
map.put(50, "deer");
for(Integer key : map.keySet()){
System.out.println(key);
}
for(String values : map.values()){
System.out.println(values);
}
}
}
Output
50
20
70
40
30
deer
tiger
cow
lion
parrot
4] Iterating using java 8 forEach () method
Using Java 8, you can iterate a map using Map.forEach() method
using lambda expression.
package com.vr.cls;
import java.util.HashMap;
import java.util.Map;
public class
DifferentIteratingMapDemo {
public static void main(String[] args) {
Map map = new HashMap();
map.put(20, "tiger");
map.put(40, "lion");
map.put(30, "parrot");
map.put(70, "cow");
map.put(50, "deer");
map.forEach( (k, v) -> System.out.println("key: "+k +" value : "+v));
}
}
Output
key: 50 value : deer
key: 20 value : tiger
key: 70 value : cow
key: 40 value : lion
key: 30 value : parrot
0 comments:
Post a Comment