How to get the longest possible key in java to match a given String
<p>I have written a code to check if a string has the key in a give Map and replace the key with the value in the string.
Below is the code</p>

<pre><code>            String s ="VamshiKrishnaA";
    Map&lt;String,String&gt; h = new HashMap&lt;String,String&gt;();
    h.put("Vamshi", "89");
    h.put("VamshiKrishnaA","dataDir");
    h.put("VamshiKrishna","dataDira");

    h.put("VamshiK", "krihsn");

    String key="";

    Iterator&lt;String&gt; i =h.keySet().iterator();
    while(i.hasNext()){
        key=i.next();
        if(s.contains(key)){
            s=s.replace(key, h.get(key));
        }
    }
    System.out.println(s);
</code></pre>

<p>When i run the above code, i got the output as dataDiraA but i need output to be dataDir.</p>

<p>I dont have control over the order of the key and values it is autogenerated.</p>

<p>Need any help in this regard</p>
