There are 100 keys and values in HashMap.how to get the keys
and values?



There are 100 keys and values in HashMap.how to get the keys and values?..

Answer / amol

Below given are 4 ways to traverse a map.
You can use entrySet or KeySet to get the keys.Then loop over these keys using iterator or for loop to get the corresponding values.

import static java.net.HttpURLConnection.*;
import java.util.*;

public class MapTest {
public static void main(String... args) {
traverseMap();
}

private static void traverseMap() {
Map<Integer, String> data = new HashMap<Integer, String>();
data.put(HTTP_OK, "HTTP_OK");
data.put(HTTP_FORBIDDEN, "HTTP_FORBIDDEN");
data.put(HTTP_NOT_FOUND, "HTTP_NOT_FOUND");

System.out.printf("%nUsing JDK 5 foreach and entry set:%n");
Set<Map.Entry<Integer, String>> entries = data.entrySet();
for(Map.Entry<Integer, String> entry : entries) {
Integer key = entry.getKey();
String value = entry.getValue();
System.out.printf("%s = %s%n", key, value);
}

System.out.printf("%nUsing Iterator<Map.Entry> and entry set:%n");
for(Iterator<Map.Entry<Integer, String>> it = entries.iterator(); it.hasNext();) {
Map.Entry<Integer, String> entry = it.next();
Integer key = entry.getKey();
String value = entry.getValue();
System.out.printf("%s = %s%n", key, value);
}

System.out.printf("%nUsing JDK 5 foreach and key set:%n");
for(Integer key : data.keySet()) {
String value = data.get(key);
System.out.printf("%s = %s%n", key, value);
}

System.out.printf("%nUsing traditional Iterator and key set%n");
for(Iterator<Integer> it = data.keySet().iterator(); it.hasNext();) {
Integer key = it.next();
String value = data.get(key);
System.out.printf("%s = %s%n", key, value);
}
}
}

Source:http://javahowto.blogspot.in/2006/06/4-ways-to-traverse-map.html

Is This Answer Correct ?    12 Yes 0 No

Post New Answer

More Core Java Interview Questions

What are the types of methods in java?

0 Answers  


What is integer valueof?

0 Answers  


Is it necessary for the port addresses to be unique? Explain with reason.

0 Answers   Aricent,


What is a superclass?

0 Answers  


what is life cycle of applet?

9 Answers  






Which is better list or arraylist in java?

0 Answers  


What is array size in java?

0 Answers  


A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.

0 Answers  


how you will prevent method overriding?

6 Answers   HCL,


What Is Resource Leak?

2 Answers  


What is the difference between throw and throws?

10 Answers   IBM,


What is hash table in java?

0 Answers  


Categories