java – How to get the key when a corresponding value is used instead? – Education Career Blog

I am using Android 2.1 SDK, the application reads from the Sqlite database, a table that has two columns, an id, and a string.

I read in this into a HashMap<Long, String>, the value part of it gets displayed in a List, now, I wish to obtain the key value, so I cooked up this simple routine:

private Map.Entry<Long, String> getEntry(String sValue){
    for (Iterator<Map.Entry<Long, String>> itMap = this.dbMap.entrySet().iterator(); itMap.hasNext();) {
        Map.Entry<Long, String> curr =;
        if (curr.getValue().equalsIgnoreCase(sValue)) return curr;
    return null;

My problem is being conscious of cpu cycles being chewed up in respect to Android, battery/cpu time, in looking for the value in the HashMap, that could be seen as a potential cycles of cpu lost.

Is there an easier and more efficient way of doing this instead of iterating?

The reasoning is that I can home in on the id, and directly delete the record from the table or even update it.


Um… it looks like the String should be the key, and the id the value. Which assumes that the Strings are unique, but so does your code.

Alternatively, can’t your list keep the ID that corresponds to an entry around invisibly? This is how you’d usually do it (e.g. in Swing or in a HTML select).


Realistically, the only way to avoid having to iterate through is to keep two HashMaps (i.e. pay the memory cost) where one HashMap is the reverse of the first. You can create the reverse-lookup HashMap when you create your forward-lookup HashMap without having to loop through your data twice. That should give you low constant time access in both directions.


If you use an Adapter you can access the ID using the getItemID() method.

Leave a Comment