Home > Java > javaTutorial > How to Sort a Two-Dimensional Array by a Specific Date Column?

How to Sort a Two-Dimensional Array by a Specific Date Column?

Susan Sarandon
Release: 2024-11-03 15:57:03
Original
389 people have browsed it

How to Sort a Two-Dimensional Array by a Specific Date Column?

Sorting a Two-Dimensional Array by a Specific Column

Problem Overview

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.

Solution using a Comparator

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>
Copy after login

Output

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template