public static void main(String[] args) {
String[] errorStr = new String[] {
"Line No: " + " " + 1,
"Line No: " + " " + 11,
"Line No: " + " " + 10,
"Line No: " + " " + 2,
"Line No: " + " " + 3
};
Arrays.sort(errorStr);
for(Object obj : errorStr){
System.out.println(obj);
}
}
Can someone point why the sorting is not working here?
expected is,
Line No: 1
Line No: 2
Line No: 3
Line No: 10
Line No: 11
Actual is,
Line No: 1
Line No: 11
Line No: 10
Line No: 2
Line No: 3
It’s sorting in lexicographic order – and lexicographically “11” comes before “2”, and “Line No: 11” comes before “Line No: 2”.
If you want “smarter” sorting, you’ll need to implement a
Comparer<String>which performs appropriate parsing in order to compare strings.If all your values are actually “Line No: ” followed by a value, I’d just transform them into an array or list of integers, as that’s the natural data you’re trying to represent… and sorting an array of
intvalues will work as you expect.Fundamentally, this is what you get for treating numbers as strings 🙂