How to get (access) values or keys of a Map in JAVA?

java_logo

There are several ways to get values or keys of a Map in JAVA. Since all maps in Java implement Map interface, following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)

Method 1: Using Iterator.
Map<String, String> map = new HashMap<String, String>();
map.put("first", "one");
map.put("second", "two");
map.put("third", "three");
map.put("four", "fourth");
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
String value = entry.getValue();
String key = entry.getKey();
System.out.println("Key = " + key + ", Value = " + value);
}

This method has its own advantages. First of all it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove().

Method 2: Using For-Each loop by Iterating entries.
This is the most common method  and  should be used if you need both map keys and values in the loop.
Map<String, String> map = new HashMap<String, String>();
map.put("first", "one");
map.put("second", "two");
map.put("third", "three");
map.put("four", "fourth");

for (Map.Entry<String, String> entry : map.entrySet()) {
String value = entry.getValue();
String key = entry.getKey();
System.out.println("Key = " + key + ", Value = " + value);
}


Method 3: Using For-Each loop by Iterating keys or values.
If you need only keys or values from the map, you can iterate over keySet or values.
Map<String, String> map = new HashMap<String, String>();
map.put("first", "one");
map.put("second", "two");
map.put("third", "three");
map.put("four", "fourth");
for (String key : map.keySet()) {
System.out.println("Key = " + key);
}
for (String value : map.values()) {
System.out.println("Value = " + value);
}

Method 4: Using For-Each loop by Iterating Keys and then search for  values.
This method  is pretty slow and inefficient as getting values by a key might be time consuming.
Map<String, String> map = new HashMap<String, String>();
map.put("first", "one");
map.put("second", "two");
map.put("third", "three");
map.put("four", "fourth");

for (String key : map.keySet()) {
String value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
Share on Google Plus

About JK STACK

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment