12

I have searched but could not find a way to print only single key, value pair for particular entry.

map.containsValue(value) or map.containsKey(key)

will only tell if particular value or key is available or not. I want to print that particular key, value pair if (value is available) In other link, They want to get the random value, if you do not know the key. Here I know key and value and want to print it for particular key and value.

Eiko
  • 25,601
  • 15
  • 56
  • 71
Hitesh Kumar
  • 512
  • 1
  • 8
  • 27
  • 3
    What about `Object value = map.get(key); if ( value != null ) { ... }`? – Thomas Jun 20 '16 at 11:41
  • 1
    Possible duplicate of [how to get the one entry from hashmap without iterating](http://stackoverflow.com/questions/1509391/how-to-get-the-one-entry-from-hashmap-without-iterating) – Julien Lopez Jun 20 '16 at 11:41
  • Julien, they want to get the random value, if you do not know the key. here i know key and values and want to print it for particular value. – Hitesh Kumar Jun 20 '16 at 11:58
  • If you have both the key _and_ the value, why do you need the map to print them? – Jorn Vernee Jun 20 '16 at 12:06
  • @HiteshKumar Right, my mistake. But if you already have the key, what's the problem? Just get the value and you have both. – Julien Lopez Jun 20 '16 at 12:07

2 Answers2

19

There is no avalilable method in https://docs.oracle.com/javase/7/docs/api/java/util/Map.html to get Entity from map if there is any key or value available. Try below code if it help :

if (map.containsKey(key)) {
   Object value = map.get(key);
 System.out.println("Key : " + key +" value :"+ value);
 }
sauumum
  • 1,638
  • 1
  • 19
  • 36
  • thanks sauumum, even i tried that before but doesn't work for me, i think i did some sily mistak, anyway thank you very much. i can't do +1 :( – Hitesh Kumar Jun 20 '16 at 12:10
0

Access pair using Key
DataType value =myMap.get(s);
Operation on value if u want (optional)
myMap.put(s,value)
and for accessing whole map use Iterator of Map.Entry set