根据数值对地图的字符串键进行排序 [英] Sorting String keys of a Map according to their numeric value

查看:112
本文介绍了根据数值对地图的字符串键进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个处理 Map< String,String []> 的类,根据数字顺序来处理它的键。为了增加侮辱伤害,一些密钥不是有效的整数,并且应该以加入的字典顺序处理。

I need to write a class that handles a Map<String, String[]>, processing its keys according to their numeric order. To add insult to injury, some keys are not valid integers, and they should be processed at the end, in acceding lexicographic order.

例如,如果密钥是:

["10", "2", "100", "duck", "black"]

他们应该按照这个顺序迭代 -

They should by iterated at this order -

["2", "10", "100", "black", "duck"]

除了迭代和尝试捕获 NumberFormatException 之外,在Java中最优雅的方法是什么?显然,我无法控制给定地图的格式。

What's the most elegant way to do it in Java, other than iterating and try-catching NumberFormatException? Obviously, I can not control the format of the given map.

推荐答案

由于您需要以特定顺序迭代,输入地图的自然顺序,您需要将其转储到另一个地图(如果您不需要每个键的相关值),则需要将其转储到另一个地图中。使用一个 TreeMap 与自定义比较器:

Since you need to iterate in a particular order that isn't the input map's natural order, you'll need to dump it into another map (or a list if you don't need the associated values for each key). Use a TreeMap with a custom comparator:

class NumbersThenWordsComparator implements Comparator<String> {
    private static Integer intValue(String s) {
        try {
            return Integer.valueOf(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public int compare(String s1, String s2) {
        Integer i1 = intValue(s1);
        Integer i2 = intValue(s2);
        if (i1 == null && i2 == null) {
            return s1.compareTo(s2);
        } else if (i1 == null) {
            return -1;
        } else if (i2 == null) {
            return 1;
        } else {
            return i1.compareTo(i2);
        }
    }       
}

public void myMethod(Map<String, String[]> originalMap) {
    TreeMap<String, String[]> t =
        new TreeMap<String, String[]>(new NumbersThenWordsComparator());
    t.putAll(originalMap);
    // now iterate over t, which will produce entries in the desired order
}

这篇关于根据数值对地图的字符串键进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆