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

Given: 1. package test; 2. 3. class Target { 4. public String name = “hello”; 5. } What can directly access and change the value of the variable name? 1 any class 2 only the Target class 3 any class in the test package 4 any class that extends Target

7 Answers   Infosys, WW,


Difference between abstract and concrete class ?

0 Answers  


why java is not supporting multiple inheritence?

3 Answers  


What is an object in Java and what are its benefits?

4 Answers   IBM,


why using interface interface ?

0 Answers  






What is a Presistent Object?

0 Answers   InfoAxon Technologies,


can we overload main method?

8 Answers   TCS,


What is the size of int in 64-bit jvm?

0 Answers  


What is the ==?

0 Answers  


Why is the singleton pattern considered to be an anti pattern?

0 Answers  


byte a=5; byte b=5; byte c=a+b; System.out.println(c); whats the o/p?

7 Answers   NIIT, Wipro,


Difference between stack and queue?

0 Answers   Flextronics,


Categories