如何从hashmap中找到最高关键值 [英] How to find highest key value from hashmap
本文介绍了如何从hashmap中找到最高关键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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(); (it1.hasNext())
{
Map.Entry pairs =(Map.Entry)it1.next();
String key_ =(String)pairs.getKey();
String value_ =(String)pairs.getValue();
finalstring = finalstring.replaceAll(key_,value_);
$ / code $ / pre
我想用最大键值进行迭代意味着键值abcd应先迭代,然后abc然后ab。 。如果您想自定义排序,您也可以传递比较器。
$ b HashMap< String,String> mapp = new HashMap< String,String>();
mapp.put(ab,blue);
mapp.put(abc,black);
mapp.put(abcd,pink);
//按字母顺序查找最大按键
字符串maxKey = Collections.max(mapp.keySet());
比较器< String> strLenCmp = new Comparator< String>(){
@Override
public int compare(String o1,String o2){
return Integer.compare(o1.length(),o2.length( ));
}
};
//通过键长查找最大键值
字符串longKey = Collections.max(mapp.keySet(),strLenCmp);
编辑:使用自定义比较器添加示例
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".
解决方案 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
这篇关于如何从hashmap中找到最高关键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文