0

I have a LinkedHashMap<String, String>, which contains some pre-populated data. Now I have a String value, which will match to a key in the above LinkedHashMap. What can I do to retrieve the very next key of the above match?

Example:

LinkedHashMap hm = new LinkedHashMap();
hm.put("a",1);
hm.put("b",2);
hm.put("c",3);
hm.put("d",4);
hm.put("e",5);

Now I have a String, say "d" . What is the optimal way if I have to retrieve the value of "e" from the above Map?

One way I have found is to convert the map key into LinkedHashSet. Now iterate the Set. Compare the value and get the next value. But isn't there any API available, which can get me all this?

Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
Programmer
  • 713
  • 1
  • 8
  • 23

2 Answers2

0

As far as I can tell, there is no way the get "the next entry after a given key" from a LinkedHashMap that is better than O(N).

Now, if you were willing to create your own version of the class (e.g. by copying the code and modifying it), then you could implement this as an O(1) operation. You might even be able to implement this as a subclass of LinkedHashMap ... but I suspect you will be stymied by the fact that some of the relevant methods and fields are not accessible from a subclass (in a different package).

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

I believe there is no straightforward way to do it but you can implement an utility method that would fulfil your need:

public class IndexedMap
{
  public static void main(String[] args)
  {
    LinkedHashMap hm = new LinkedHashMap();
    hm.put("a",1);
    hm.put("b",2);
    hm.put("c",3);
    hm.put("d",4);
    hm.put("e",5);
    System.out.println(getNextItem(hm, "d"));
  }

  public static Object getNextItem(LinkedHashMap<String, String> hMap, String item){

    int index = 0;
    List<String> keys = new ArrayList<String>(hMap.keySet());
    for (String key : keys)
    {
      if (item.equals(key))
        break;

      index++;
    }
    return (index < keys.size() - 1) ? hMap.values().toArray()[++index] : 0;
  }

}
tmarwen
  • 15,750
  • 5
  • 43
  • 62