Java排序映射<string,string> by String prefix </string,string>

时间:2013-06-25 14:21:19

标签: java list sorting map treemap

在Java中。 如何使用带有数字前缀的给定字符串对地图进行排序。 我从属性文件中获取地图:

1_aaa=bla1
2_bbb=bla2
3_ccc=bla3
4_ddd=bla4 
...
10_jjj=bla10
11_kkk=bla11
12_lll=bla12

我正在从文件中加载属性:

FileInputStream is =new FileInputStream(new File(filePath));
Properties prop = new Properties();
prop.load(is);

之后: SortedMap<Object, Object> sortedProperties new TreeMap<Object, Object>(prop);

现在使用TreeMap时 - &gt; '10_jjj'是SortedMap中的第一个元素 我希望'1_aaa'成为第一个。

有什么想法吗?

由于

5 个答案:

答案 0 :(得分:6)

行为是因为0 comes before _ in the ASCII table

为了得到你想要的东西,写下你的Comparator<String>并比较前缀的字符串,然后使用TreeMap(Comparator)构造函数构建地图。

没有任何错误检查的简单示例等:

class Cmp implements Comparator<String> {
    @Override
    public int compare(String a, String b) {
        return prefixNum(a) - prefixNum(b);
    }

    private int prefixNum(String a) {
        return Integer.parseInt(a.split("_")[0]);
    }
}

然后像这样实例化地图:

TreeMap<String, String> map = new TreeMap<String, String>(new Cmp());

答案 1 :(得分:2)

您必须创建自己的Comparator才能完成此任务。

在创建TreeMap期间,您可以将此Comparator提供给Map,然后按照您实施的方式对其进行排序。

答案 2 :(得分:0)

您需要将前缀转换为整数,然后对它们进行排序,例如

int prefix = Integer.parseInt(str.substring(0, str.indexOf("_"))); // sort/compare on this

答案 3 :(得分:0)

以下是工作代码:

class ComparatorOfNumericString implements Comparator<String>{

    public int compare(String o1, String o2) {
        // TODO Auto-generated method stub
        String a[] = o1.split("_");
        String b[] = o2.split("_");
        return Integer.parseInt(a[0])-Integer.parseInt(b[0]);
    }
}

答案 4 :(得分:0)

这应该做你需要的事情

    Properties p = new Properties();
    p.setProperty("1_aaa", "blah");
    p.setProperty("10_aaa", "blah");

    Comparator<Object> c = new Comparator<Object>()
    {
        @Override
        public int compare(Object o1, Object o2)
        {
            String s1 = (String)o1;
            String s2 = (String)o2;

            Integer i1 = Integer.valueOf(s1.substring(0, s1.indexOf('_')));
            Integer i2 = Integer.valueOf(s2.substring(0, s2.indexOf('_')));

            return i1.compareTo(i2);
        }
    };

    SortedMap<Object, Object> sortedProperties = new TreeMap<Object, Object>(c);
    sortedProperties.putAll(p);

    System.out.println(sortedProperties.firstKey());