user1578363
user1578363

Reputation:

Getting the key and its specific value from map

I am using Map as follows

Map<String, String> propMap = new LinkedHashMap<String, String>();

and I saw that there is two methods that I can use keySet() (to get the list of keys) and values to get the list of values but my question is how to relate between them for example for key1 the value is 2.

I thought to use get value like follows

    Map<String, String> propMap2 = propterm.getPropMap();
    Set<String> keySet = propMap2.keySet();

But how I relate it to his respective value ?

Upvotes: 1

Views: 2045

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213213

You can use propMap.entrySet() method which returns a Map.Entry of key, value, if you want to use every pair of key and value: -

for (Map.Entry<String, String> entry: propMap.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

Or, if you want to know how to do this with propMap.keySet(), you can iterate over the Set<Key> you obtain, and for each key, use propMap.get(key), to get the value of a particular key: -

Set<String> keySet = propMap2.keySet();

for (String key: keySet) {
    System.out.println(propMap.get(key));
}

From an answer from this post: -

With the later approach, if you are regularly accessing the key-value pair, then for each key, the map.get() method is called, which - in the case of a HashMap - requires that the hashCode() and equals() methods of the key object be evaluated in order to find the associated value*. In the first case (entrySet), that extra work is eliminated.

Upvotes: 5

Related Questions