How to iterate over each entry of the hashmap

0

 


If you are preparing for the technical interview and if your primary language is java then prepare this question. THis question is mostly asked by the interviewer to see the depth of your knowledge. It is very important for you to learn the concept of it . 


What is hashmap :

In Java HashMap is a class which implements the Map interface. Hashmap stores the data in the key and value pair, where keys should be unique.


import java.util.*;
public class HindiCodingCommunity{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(1,"India"); //Put elements in Map
hm.put(2,"USA");
hm.put(3,"UK");
hm.put(4,"Russia");
}
}


So let's see how can we iterate over each entry of the hashmap. 

Using iterator and Map.Entry


long i = 0;
Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Integer> pair = it.next();
i += pair.getKey() + pair.getValue();
}





Using keySet and foreach



long i = 0;
for (Integer key : map.keySet()) {
i += key + map.get(key);
}


Using foreach and Map.Entry

long i = 0;
for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
i += pair.getKey() + pair.getValue();
}


Using for and Map.Entry



long i = 0;
for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {
Map.Entry<Integer, Integer> entry = entries.next();
i += entry.getKey() + entry.getValue();
}



Using keySet and iterator



long i = 0;
Iterator<Integer> itr2 = map.keySet().iterator();
while (itr2.hasNext()) {
Integer key = itr2.next();
i += key + map.get(key);
}


Using forEach from Java 8


final long[] i = {0};
map.forEach((k, v) -> i[0] += k + v);










Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !