简体   繁体   English

根据密钥大小对HashMap密钥进行排序

[英]Sort HashMap keys based on the key size

I have a HashMap in which keys are Strings . 我有一个HashMap ,其中的键是Strings I need to take the keys and sort it based on the key size ie String length and then store it in some ArrayList . 我需要获取密钥并根据密钥大小(即字符串长度)对其进行排序,然后将其存储在某些ArrayList

Note: If two keys size is same, then we can place it in any order. 注意:如果两个键的大小相同,那么我们可以按任何顺序放置它。

For eg. 例如。

hm.put("abc","hi");
hm.put("A","hi");
hm.put("ab","hi");
hm.put("a","hi");

My ArrayList should have elements in order abc,ab,a,A . 我的ArrayList应该具有顺序为abc,ab,a,A元素。

Can someone let me know what's the best possible way to do it. 有人可以让我知道最好的方法是什么。

You can sort the keys by length using a custom Comparator like this: 您可以使用自定义Comparator按长度对键进行排序,如下所示:

List<String> s = new ArrayList<>(hm.keySet());
Collections.sort(s, new Comparator<String>(){
            @Override
            public int compare(String s1, String s2){
                 return Integer.compare(s2.length(), s1.length());
            }
});


Another possibility would be to use a TreeSet providing also here a custom Comparator to its constructor. 另一种可能性是使用TreeSet在此处还为其构造函数提供自定义Comparator

TreeSet<String> ts = new TreeSet<>(new Comparator<String>(){
                     @Override
                     public int compare(String s1, String s2){
                           int cmp = Integer.compare(s2.length(), s1.length());
                           return cmp != 0 ? cmp : s1.compareTo(s2);
                     }
});
ts.addAll(hm.keySet());

Just note here that if the length of the pair of Strings you compare is the same, you have to compare also their lexicographical order, otherwise the TreeSet would just contains the Strings that have different length (ie either "a" or "A" wouldn't be added to the set) 请注意,如果您比较的一对Strings的长度相同,则还必须比较它们的字典顺序,否则TreeSet将只包含具有不同长度的Strings (即“ a”或“ A”会不会添加到集合中)

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

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