Sometimes it's necessary to use a custom Comparator when sorting in Java. Take the example below. We want to sort these 'decimals' but of course they're of type String so "19" will be less than "2". Because we have the decimal point represented by 'pt', we need to do something more specialised than simply Double.parseDouble(string), which can be done as below. First, this is how the List is produced.
String[] t = { "1", "19", "2", "3pt1", "3", "5pt1", "6pt2", "7pt3", "7pt3" };
List inputList = new ArrayList(Arrays.asList(t));
public static void sort(List list) {
Collections.sort(list,
new Comparator<String>() {
public int compare(String s1, String s2) {
int result = 0;
double val1;
double val2;
String[] temp1 = s1.split("pt");
String[] temp2 = s2.split("pt");
if (temp1.length > 1) {
val1 = Double.parseDouble(new StringBuilder().append(
temp1[0]).append('.').append(temp1[1])
.toString());
} else {
val1 = Double.parseDouble(s1);
}
if (temp2.length > 1) {
val2 = Double.parseDouble(new StringBuilder().append(
temp2[0]).append('.').append(temp2[1])
.toString());
} else {
val2 = Double.parseDouble(s2);
}
if (val1 > val2) {
result = 1;
} else if (val2 > val1) {
result = -1;
} else {
result = 0;
}
return result;
}
});
}