简体   繁体   English

如何从hashmap中找到最高键值

[英]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". 我想用最大键值迭代意味着键值“abcd”应首先迭代然后“abc”然后“ab”。

Here is an example using Collections.max(). 以下是使用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 编辑 :添加自定义Comparator的示例

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存储数据。

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. 尝试使用TreeMap而不是HashMap,它有获取最后一个条目的方法,它将为您提供具有最高键值的条目。 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中,如果您传递自定义比较器,那么它将以一种方式排序,您将获得具有最大值的键,因此您不必担心它。

TreeMap - lastEntry TreeMap - lastEntry

Refer this link, and lastEntry method. 请参阅此链接和lastEntry方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM