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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With