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

Explain what do you mean by functional overloading in java?

557


What is off heap memory?

550


Explain hashset and its features?

583


How do you break a loop?

566


Which language is java?

546






Are the imports checked for validity at compile time? Will the code containing an import such as java.lang.abcd compile?

596


Explain about complier design(phases)

632


When do you call copy constructor?

556


How do you take thread dump in java?

560


How to store image in arraylist in java?

512


Explain Basics of OOP Language in java

593


What is the use of hashmap in java?

557


How many ways can we create the string object?

532


Write a program to search a number in the given list of numbers.

631


Why string is not a wrapper class?

646