How to iterate hashmap with highest String key value

HashMap<String, String> mapp=new HashMap<String, String>();
mapp.put(“ab”,“blue”);
mapp.put(“abc”,“black”);
mapp.put(“abcef”,“black”);
mapp.put(“abcd”,“pink”);
for (Iterator it = alltyp.iterator(); it.hasNext():wink: {
String finalstring = (String) it.next();

                          Iterator it1=mapp.entrySet().iterator();
                          while(it1.hasNext())
                          {
                              Map.Entry pairs = (Map.Entry) it1.next();
                              String key_ = (String) pairs.getKey();
                              String value_ = (String) pairs.getValue();
                              finalstring = finalstring.replaceAll(key_, value_);

                          }

                      }

I want to iterate with max key value means key value “abcdef” should iterate first then “abcd” then “abc”. so that my replaceall function should replace highest value first.

A hash map is not sorted and you can not force it to do so. Use a sorted implementation instead, i.e. TreeMap.

There is one constructor of TreeMap that takes a comparator, so you can give it your own sorting order, see TreeMap Constructor with Comparator.

//