Java 如何从哈希图中找到最高的键值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24200973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find highest key value from hashmap
提问by user3441816
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".
我想用最大键值迭代意味着键值“abcd”应该先迭代,然后是“abc”,然后是“ab”。
回答by Tim B
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:
选项1:
Create an ArrayList, dump all the keys from the map into it.
创建一个 ArrayList,将地图中的所有键转储到其中。
Sort the ArrayList, iterate over the sorted ArrayList.
对 ArrayList 进行排序,遍历已排序的 ArrayList。
Option 2:
选项 2:
Use a TreeMap to store the data.
使用 TreeMap 来存储数据。
回答by Bilbo Baggins
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 而不是 HashMap 它具有获取最后一个条目的方法,该方法将为您提供具有最高键值的条目。即使在 TreeMap 中,如果您传递自定义 Comparator ,那么它将以首先获得具有最大值的键的方式对其进行排序,因此您不必担心它。
Refer this link, and lastEntry method.
请参阅此链接和 lastEntry 方法。
回答by David Roussel
Here is an example using Collections.max(). You can also pass a comparator if you want a custom ordering.
这是一个使用 Collections.max() 的示例。如果您想要自定义排序,也可以传递比较器。
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
编辑:添加带有自定义比较器的示例