I have a HashMap with String key and String value. I want to get an item from list, I tried to give key and wanted to get value but it gives an error. The following example how can I get "both" value with give the key "blazer"?
HashMap<String,String> upper = new HashMap<>();
upper.put("shoulder","both");
upper.put("blazer","both");
if(upper.get(upper.get("blazer"))) {} //gives an "incompatible types" error.
//Error: Required: boolean Found: java.lang.String
They way you have it there upper.get(upper.get("blazer"));
would just return null.
You're passing in upper.get("blazer")
(which would return "both") to your outer upper.get
. Since you have no "both" key stored in your map, it returns null.
Should be:
upper.get("blazer");
Understand that upper.get(key)
will not return a boolean
value. You have defined your HashMap
as follows:
HashMap<String,String> upper = new HashMap<>();
This means that both the key
and value
will be of type String
. Thus, providing a valid key
the the get()
method will return a String
:
String myValue = upper.get("blazer");
If you wish to check if a key
is available before you attempt to read the value you can use the method containsKey()
with will return a boolean
value indicating whether the HashMap
contains an entry with the given key
:
if(upper.containsKey("blazer")){
String myValue = upper.get("blazer");
Log.e(TAG, "Yes blazer is available : " + myValue);
}
else{
Log.e(TAG, "No blazer is available!");
}
You can also iterate through the available key
s like this:
Set<String> set = map.keySet();
for(String s : set){
Log.e(TAG, "Map key = " + s + " value = " + map.get(s));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.