Organizational Research By

Surprising Reserch Topic

get string value from HashMap depending on key name in java collection


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 ;)

asked Jun 19, 2015 in Core java by rajesh
0 votes
65 views



Related Hot Questions

2 Answers

0 votes
Just use Map#get(key) ?

Object value = map.get(myCode);
Here's a tutorial about maps, you may find it useful: http://java.sun.com/docs/books/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;
}
answered Jun 19, 2015 by rajesh
0 votes
If you are storing keys/values as strings, then this will work:

HashMap newMap = new HashMap();
newMap.put("my_code", "shhh_secret");
String value = (String) newMap.get("my_code");
The question is what gets populated in the HashMap (key & value)
answered Jun 19, 2015 by rajesh

...