Given a two-dimensional array containing rows of data with two columns, where the first column represents a date in the "yyyy.MM.dd HH:mm" format and the second column is a String, we aim to sort the array based on the first column.
To sort the array, we can utilize the Arrays.sort() method along with a custom comparator. The comparator will compare the first elements of each row, which represent the dates.
<code class="java">import java.util.Arrays; import java.util.Comparator; public class ArraySorter { public static void main(String[] args) { // Input array String[][] data = { {"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"} }; // Create a comparator to sort based on the first column (date) Comparator<String[]> comparator = Comparator.comparing(row -> row[0]); // Sort the array using the comparator Arrays.sort(data, comparator); // Print the sorted array for (String[] row : data) { System.out.println(row[0] + " " + row[1]); } } }</code>
The output will display the sorted data, with rows arranged in ascending order based on the first column (date):
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 above is the detailed content of How to Sort a Two-Dimensional Array by a Specific Date Column?. For more information, please follow other related articles on the PHP Chinese website!