131

I have a HashMap with various keys and values, how can I get one value out?

I have a key in the map called my_code, it should contain a string, how can I just get that without having to iterate through the map?

So far I've got..

   HashMap newMap = new HashMap(paramMap);
   String s = newMap.get("my_code").toString();

I'm expecting to see a String, such as "ABC" or "DEF" as that is what I put in there initially, but if I do a System.out.println() I get something like java.lang.string#F0454

Sorry, I'm not too familiar with maps as you can probably guess ;)

10 Answers 10

173

Just use Map#get(key) ?

Object value = map.get(myCode);

Here's a tutorial about maps, you may find it useful: https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html.

Edit: you edited your question with the following:

I'm expecting to see a String, such as "ABC" or "DEF" as that is what I put in there initially, but if I do a System.out.println() I get something like java.lang.string#F0454

Sorry, I'm not too familiar with maps as you can probably guess ;)

You're seeing the outcome of Object#toString(). But the java.lang.String should already have one implemented, unless you created a custom implementation with a lowercase s in the name: java.lang.string. If it is actually a custom object, then you need to override Object#toString() to get a "human readable string" whenever you do a System.out.println() or toString() on the desired object. For example:

@Override
public String toString() {
    return "This is Object X with a property value " + value;
}
3
  • 2
    Of course, if you are creating a custom string class, I would recommend (1) not doing that, since it's probably not what you want to do, and (2) if you are going to do that, DO NOT put it in the java.lang namespace.
    – Tyler
    Jul 1, 2010 at 18:44
  • 1
    if HashMap<String, String> newMap = new HashMap<String, String>(); how to get string element from this...? where String value = newMap.get("my_code"); gives error Jan 19, 2013 at 7:26
  • how you can inverse ? get key from value ?
    – user3402040
    Nov 16, 2015 at 13:32
58

If you are storing keys/values as strings, then this will work:

HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("my_code", "shhh_secret");
String value = newMap.get("my_code");

The question is what gets populated in the HashMap (key & value)

2
  • if HashMap<String, String> newMap = new HashMap<String, String>(); how to get string element from this...? where String value = newMap.get("my_code"); gives error Jan 19, 2013 at 7:24
  • don't the two "my_code" strings have different references? why does this work?
    – user5730329
    Jul 27, 2021 at 16:57
11

If you will use Generics and define your map as

Map<String,String> map = new HashMap<String,String>();

then fetching value as

 String s = map.get("keyStr"); 

you wont be required to typecast the map.get() or call toString method to get String value

9

Your question isn't at all clear I'm afraid. A key doesn't have a "name"; it's not "called" anything as far as the map is concerned - it's just a key, and will be compared with other keys. If you have lots of different kinds of keys, I strongly suggest you put them in different maps for the sake of sanity.

If this doesn't help, please clarify the question - preferrably with some code to show what you mean.

7

map.get(myCode)

6

An important point to be noted here is that if your key is an object of user-defined class in java then make it a point to override the equals method. Because the HashMap.get(Object key) method uses the equals method for matching the key value. If you do not override the equals method then it will try to find the value simply based on the reference of the key and not the actual value of key in which case it will always return a null.

0
3

Suppose you declared HashMap as :-

HashMap<Character,Integer> hs = new HashMap<>();

Then,key in map is of type Character data type and value of int type.Now,to get value corresponding to key irrespective of type of key,value type, syntax is :-

    char temp = 'a';
    if(hs.containsKey(temp)){
`       int val = hs.get(temp); //val is the value corresponding to key temp
    }

So, according to your question you want to get string value corresponding to a key.For this, just declare HashMap as HashMap<"datatype of key","datatype of value" hs = new HashMap<>(); Using this will make your code cleaner and also you don't have to convert the result of hs.get("my_code") to string as by default it returns value of string if at entry time one has kept value as a string.

1

This is another example of how to use keySet(), get(), values() and entrySet() functions to obtain Keys and Values in a Map:

        Map<Integer, String> testKeyset = new HashMap<Integer, String>();

        testKeyset.put(1, "first");
        testKeyset.put(2, "second");
        testKeyset.put(3, "third");
        testKeyset.put(4, "fourth");

        // Print a single value relevant to a specified Key. (uses keySet())
        for(int mapKey: testKeyset.keySet())
            System.out.println(testKeyset.get(mapKey));

        // Print all values regardless of the key.
        for(String mapVal: testKeyset.values())
            System.out.println(mapVal.trim());

        // Displays the Map in Key-Value pairs (e.g: [1=first, 2=second, 3=third, 4=fourth])
        System.out.println(testKeyset.entrySet());
0

You can use the get(Object key) method from the HashMap. Be aware that i many cases your Key Class should override the equals method, to be a useful class for a Map key.

0
 HashMap<Integer, String> hmap = new HashMap<Integer, String>();
 hmap.put(4, "DD");

The Value mapped to Key 4 is DD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.