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".
max(someMap) will return the max Key, when you want the key that corresponds to the max value.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With