Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sorting map<String,String> by String prefix

In Java. How do I sort a map by given string with numeric prefix. I get the map from properties file:

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

I am loading the properties from file:

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

and after: SortedMap<Object, Object> sortedProperties new TreeMap<Object, Object>(prop);

Now when using TreeMap --> '10_jjj' is the first element in the SortedMap and I want '1_aaa' to be the first.

Any ideas?

Thanks

like image 598
user2520395 Avatar asked Apr 20 '26 23:04

user2520395


1 Answers

The behavior is because 0 comes before _ in the ASCII table.

To get want you want, write your Comparator<String> and compare the Strings base on the prefix, then use the TreeMap(Comparator) constructor to construct the map.

A simple sample without any error checking, etc.:

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]);
    }
}

Then instantiate the map like this:

TreeMap<String, String> map = new TreeMap<String, String>(new Cmp());
like image 163
zw324 Avatar answered Apr 23 '26 15:04

zw324