how to iterate hashmap in java
1)
import java.util.*;
public class Test{
public static void main(String args[]) {
HashMap<Integer,String> hm = new HashMap<>();
hm.put(1,"raja");
hm.put(2,"ram");
hm.put(3,"mohan");
hm.put(4,"roy");
for(Map.Entry<Integer,String> e : hm.entrySet()){
System.out.println(e.getKey() + " "+e.getValue());
}
}
}
2)
Code:
import java.util.*;
public class Test{
public static void main(String args[]) {
HashMap<Integer,String> hm = new HashMap<>();
hm.put(1,"raja");
hm.put(2,"ram");
hm.put(3,"mohan");
hm.put(4,"roy");
//keys
for(int i : hm.keySet()){
System.out.print(i+" ");
}
System.out.println();
for(String s : hm.values()){
System.out.print(s+" ");
}
System.out.println();
}
}
3)
import java.util.*;
public class Test{
public static void main(String args[]) {
HashMap<Integer,String> hm = new HashMap<>();
hm.put(1,"raja");
hm.put(2,"ram");
hm.put(3,"mohan");
hm.put(4,"roy");
Iterator<Map.Entry<Integer,String>> itr = hm.entrySet().iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
4)
import java.util.*;
public class Test{
public static void main(String args[]) {
HashMap<Integer,String> hm = new HashMap<>();
hm.put(1,"raja");
hm.put(2,"ram");
hm.put(3,"mohan");
hm.put(4,"roy");
hm.forEach((k,v)->System.out.println(k+"="+v));
}
}
Comments
Post a Comment