Question

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.

Was it helpful?

Solution

You have a map that maps Integers to Strings, not the other way around. To find the (potentially multiple) Integer keys associated with a given String value, you can loop over the Maps 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.

OTHER TIPS

Or you could do:

public Integer getAssociatedInt(Person p){
    for(final int i : people.keySet())
        if(people.get(i).equals(p.toString()))
            return i;
    // else no key found, return no key (null is the only way to capture this).
    return null;
}

Try this:

public HashMap<Integer, String> people;

public int getAssociatedInt(Person p){
    int indexOfPerson = -1;
    if (p != null) {
        for (int i = 0; i < people.size(); ++i) {
            if (p.equals(people.get(i)) {
                indexOfPerson = i;
                break;
            }
        }
    }
    return indexOfPerson;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top