How to find highest key value from hashmap

旧街凉风 提交于 2019-12-10 14:48:42

问题


iterate with max key value so that it will replace max string value. first My code is

HashMap<String, String> mapp=new HashMap<String, String>();
mapp.put("ab","blue");
mapp.put("abc","black");
mapp.put("abcd","pink");
for (Iterator it = alltyp.iterator(); it.hasNext();) {
    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 "abcd" should iterate first then "abc" then "ab".


回答1:


Here is an example using Collections.max(). You can also pass a comparator if you want a custom ordering.

HashMap<String, String> mapp=new HashMap<String, String>();
mapp.put("ab","blue");
mapp.put("abc","black");
mapp.put("abcd","pink");

// find max key alphabetically
String maxKey = Collections.max(mapp.keySet());


Comparator<String> strLenCmp = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return Integer.compare(o1.length(), o2.length());
    }
};

// find max key by key length
String longKey = Collections.max(mapp.keySet(), strLenCmp);

Edit: added example with custom Comparator




回答2:


Use Generics, get rid of the casting. That will tidy up your code a lot.

You will need a custom comparator to do the sorting.

Once you have the comparator you have two choices:

Option 1:

Create an ArrayList, dump all the keys from the map into it.

Sort the ArrayList, iterate over the sorted ArrayList.

Option 2:

Use a TreeMap to store the data.




回答3:


Try using the TreeMap instead of HashMap it has the method for getting the last entry which will give you the entry which has the highest value of key. Even in TreeMap if you pass your custom Comparator then it will be sorted in a way that you will get the key with max value first so you don't have to worry about it.

TreeMap - lastEntry

Refer this link, and lastEntry method.



来源:https://stackoverflow.com/questions/24200973/how-to-find-highest-key-value-from-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!