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

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

FOR EXAMPLE WE R HAVING TWO LIST ELEMENTS ..BOTH LISTS CONTAINS ID,NAME,PLACE ..I NEED TO COMPARE BOTH IDS IN TWO LISTS,IF ID'S R SAME MEANS WE HAVE ADD THE DETAILS(LIKE NAME,PLACE) TO MAP...HOW IS POSSIBLE ?CAN ANY ONE SUGGEST?

2630


Is java ee a framework?

516


What is a boolean flag in java?

559


Explain the difference between intermediate and terminal operations in java8?

564


What are access specifiers in java ?

588






How to disable caching on back button of the browser?

525


Can a variable be local and static at the same time?

542


Do we have pointers in java?

524


Can abstract class have private constructor?

494


Explain the difference between treeset and treemap in java?

525


what type of questions asked for barclays technologies pune please send urgent

5226


Why do we use return statement?

535


How do you convert string to int in java?

558


What are the java ide's? Explain

523


What kind of variables a class can consist of?

630