Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find highest key value from hashmap

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

like image 749
user3441816 Avatar asked Jun 13 '14 08:06

user3441816


People also ask

How do you find the maximum value of a Map?

max(someMap) will return the max Key, when you want the key that corresponds to the max value.

How do I find the highest value in Java?

The max() method is an inbuilt method of Math class which is present in java. lang package that is used to find the maximum of two numbers. The max() method takes two inputs that are of types numbers, i.e., int, long, float, double, and returns the maximum of the given numbers.

How do I find the key of a HashMap?

util. HashMap. containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.


1 Answers

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

like image 131
David Roussel Avatar answered Oct 24 '22 11:10

David Roussel