How to find highest key value from hashmap

31,834

Solution 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

Solution 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.

Share:
31,834
user3441816
Author by

user3441816

Updated on March 22, 2020

Comments

  • user3441816
    user3441816 about 4 years

    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".