I have a List of objects each of which has a method getNumOrder that returns a string. The objects in the list are sorted in lexicographical order. Most of the times all the objects in the list have getNumOrder that return an integer (but not always).
If all the elements in the lists have NumOrders that are integers I would like to sort them using integer sort order. Otherwise they will remain sorted lexicographically.
I have tried this using Java 8 Lambdas
try {
results.sort((r1,r2)-> {
Integer seq1= new Integer(r1.getNumOrder());
Integer seq2= new Integer(r2.getNumOrder());
seq1.compareTo(seq2);
});
}
catch (Exception e) {
// Do nothing: Defaults to lexicographical order.
}
There are 2 issues:
Because I dont know Lambda expressions very well the syntax is incorrect
I am not sure if this will work if the sorting by integer order fails, i.e. whether it will leave the list sorted lexicographically.
Comparator.comparingInt(r -> Integer.parseInt(r.getNumOrder())).sort()method. It's basically a shorter equivalent to Andreas' answer.