简体   繁体   English

如何通过Java的数字字符串键对Map进行排序

[英]How to sort a Map in Java by its String keys which are numeric

I have created a map called result . 我已经创建了一个名为result的地图。

In the sortByKeys method as my keys are String with Numeric values, I have converted them to Integer key type Map then sorted them. sortByKeys方法中,因为我的键是带有数字值的字符串,所以我将它们转换为Integer键类型Map,然后对其进行了排序。

The sorting is working fine when I am looping and printing individually, but not when I am setting them in another Map. 当我单独循环和打印时,排序工作正常,但是当我在另一个地图中设置它们时,排序不能正常工作。

public class TestDate {
    public static void main (String args[]){

    Map<String, String> result = new HashMap<String, String>();

        result.put("error", "10");
        result.put("1","hii");
        result.put("Update","herii");
        result.put("insert","insert");
        result.put("10","hiiuu");
        result.put("7","hii");
        result.put("21","hii");
        result.put("15","hii"); 

        Map<String, String> sorted = sortByKeys(result);
        //System.out.println(sorted);   
    }

    private static Map<String, String> sortByKeys(Map<String, String> map) {
        Map <Integer,String> unSorted = new  HashMap<Integer, String>();
        Map <String,String> sorted = new  HashMap<String, String>();
        for (Map.Entry<String, String> entry : map.entrySet())
        {
            try{
                int foo = Integer.parseInt(entry.getKey());            
                unSorted.put(foo, entry.getValue());                
            }catch (Exception e){

            }
        }
        Map<Integer, String> newMap = new TreeMap<Integer, String>(unSorted); 
        Set set = newMap.entrySet();
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            Map.Entry me = (Map.Entry)iterator.next();
            System.out.println(me.getKey());
            System.out.println(me.getValue());
            sorted.put(me.getKey().toString(),  me.getValue().toString());

       }
        System.out.println(sorted);

        return null;
    }   
}

Here is the o/p : 这是o / p:

1
hii
7
hii
10
hiiuu
15
hii
21
hii
{21=hii, 10=hiiuu, 1=hii, 7=hii, 15=hii}

If you don't need the last inch of performance, you can solve this rather directly, without an extra step to sort the map, by using SortedMap : 如果您不需要性能的最后一英寸,则可以使用SortedMap直接解决此问题,而无需执行其他步骤即可对地图进行排序:

Map<String,String> result = new TreeMap<>(Comparator.comparingInt(Integer::parseInt));

If you are among the unfortunate bunch who are still being denied access to Java 8, you'll have to implement the Comparator in long-hand: 如果不幸的一类人仍然被拒绝访问Java 8,则必须长期实施Comparator

new TreeMap<>(new Comparator<String,String> { public int compare(String a, String b) {
  return Integer.compare(Integer.parseInt(a), Integer.parseInt(b));
}});

The above approach works only under the assumption that all keys are parseable integers. 上面的方法仅在所有键都是可解析整数的假设下起作用。 If that is not the case, then you won't be able to use the SortedMap directly, but transform your original map into it, filtering out the unparseable keys. 如果不是这种情况,那么您将无法直接使用SortedMap ,而是将原始地图转换成它,过滤掉无法解析的键。

It's because the Map you're putting them into is a HashMap , which isn't sorted. 这是因为您要放入的MapHashMap ,未排序。 There's no guarantee of the ordering of results you'll get out of the HashMap , even if you put them in in the right order. 即使您以正确的顺序放置结果,也无法保证您会从HashMap得到结果。

(And calling it sorted doesn't change anything :) ) (并且将其sorted不会改变任何内容:))

You print 2 different maps and not the same: you iterate over and print the entries of newMap map, and at the end you print sorted map. 您打印了2张不同的地图,但并不相同:您遍历并打印newMap地图的条目,最后打印sorted地图。

You see the sorted entries printed because you iterate over your sorted newMap . 您看到已排序的条目已打印,因为您遍历了已排序的newMap

Then you print the sorted map which is unsorted (despite by its name). 然后,您将打印未排序sorted地图(尽管其名称)。 You print a different map instance. 您打印另一个地图实例。

Print this: 打印此:

System.out.println(newMap); // This is the instance of the sorted "TreeMap"

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

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