How to print all log lines containing a specific date from a text block in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

// find all log lines with a given date
public class FindAllLogsByDate {

    public static List<String> findAllLogsByDate(String logs, String targetDate) {
        List<String> matches = new ArrayList<>();

        String[] lines = logs.split("\n");
        for (String line : lines) {
            if (line.contains(targetDate)) {
                matches.add(line);
            }
        }

        return matches;
    }

    public static void main(String[] args) {
        String logs =
            "01/12/2023 - Log entry one.\n" +
            "17/03/2021 - Log entry two.\n" +
            "29/07/2019 - Log entry three.\n" +
            "05/11/2024 - Log entry four.\n" +
            "22/08/2020 - Log entry five.\n" +
            "14/02/2018 - Log entry six.\n" +
            "30/09/2022 - Log entry seven.\n" +
            "11/06/2017 - Log entry eight.\n" +
            "03/04/2025 - Log entry nine.\n" +
            "05/11/2024 - Log entry ten.\n";

        List<String> results = findAllLogsByDate(logs, "05/11/2024");

        for (String r : results) {
            System.out.println(r);
        }
    }
}


/*
run:

05/11/2024 - Log entry four.
05/11/2024 - Log entry ten.

*/

 



answered 10 hours ago by avibootz

Related questions

...