I want to know how to get the Integer that is associated with the String in the HashMap people:
public HashMap<Integer, String> people;
public int getAssociatedInt(Person p){
return (The thing I do not know how to get);
}
I already tried people.get();, but I'm not exactly sure how to do that.
You have a map that maps Integer
s to String
s, not the other way around. To find the (potentially multiple) Integer
keys associated with a given String
value, you can loop over the Map
s entrySet()
:
for (Entry<Integer, String> e : people.entrySet())
if (e.getValue().equals(value))
return e.getKey();
However, the method above doesn't deal with multiple keys mapping to the same value. If you want to handle that, you can keep a list of target keys and add to the list instead of return in the body of the if
-statement.
An alternate method would be to maintain a "reverse" map that maps the strings to the integers, and then simply query that.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments