In Java, I have a data in my array like the following
2009.07.25 20:24 Message A
2009.07.25 20:17 Message G
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 20:01 Message F
2009.07.25 21:08 Message E
2009.07.25 19:54 Message R
I would like to sort it based on the first column, so my final data can look like this
2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E
The first column is a date of format "yyyy.MM.dd HH:mm" and the second column is a String.
install java8 jdk+jre
use lamda expression to sort 2D array.
code:
output
This way you can handle any type of data in those arrays (as long as they're Comparable) and you can sort any column in ascending or descending order.
PS: make sure you check for
ArrayIndexOutOfBounds
and others.EDIT: The above solution would only be helpful if you are able to actually store a
java.util.Date
in the first column or if your date format allows you to use plain String comparison for those values. Otherwise, you need to convert that String to a Date, and you can achieve that using a callback interface (as a general solution). Here's an enhanced version:And at this point, you can sort on your first column with:
I skipped the checks for nulls and other error handling issues.
I agree this is starting to look like a framework already. :)
Last (hopefully) edit: I only now realize that your date format allows you to use plain String comparison. If that is the case, you don't need the "enhanced version".
Check out the ColumnComparator. It is basically the same solution as proposed by Costi, but it also supports sorting on columns in a List and has a few more sort properties.
Assuming your array contains strings, you can use the following:
If you have a two-dimensional array, the solution is also very similar:
Using Lambdas since java 8:
Output: