Search code examples
javadatetimearraylistdate-comparisonlocaldate

Search arraylist for LocalDateTime range


Need some help with the code to return a range of dates from an arrayList after user input.

ArrayList mainList

static ArrayList<LEntry> mainList = new ArrayList();

public LEntry(LocalDateTime date, String id)
    2018-10-23T12:05:22 A2315
    2017-01-13T10:09:30 A2253
    2018-05-10T18:55:30 V1225
    2018-05-03T17:44:50 R9952
    2017-06-15T16:25:31 A2253

My unsuccessful code:

private static ArrayList<LogEntry> range() {
    String sDate, eDate;
    LocalDateTime startDate, endDate;

    System.out.println("Start date:\n");
    sDate = in.nextLine().replace(" ", "T");
    System.out.println("End date:\n");
    eDate = in.nextLine().replace(" ", "T");

    //System.out.println(eDate);
    startDate = LocalDateTime.parse(sDate, DateTimeFormatter.ISO_DATE_TIME);
    endDate = LocalDateTime.parse(eDate, DateTimeFormatter.ISO_DATE_TIME);

    mainList.stream().filter(i -> i.date ?? ((startDate.isBefore(i.date))&&(endDate.isAfter(i.date))).forEach(j -> Ranges.add(0, j));

    return Ranges;
}

I'm trying to use isBefore and isAfter to get my range but since they return true/false I'm having some trouble integrating it on my code.

My goal is to get the LEntries between the given dates.
Thank you for any help.

Solved, thank you @user7

mainList.stream()
    .filter(i -> startDate.isBefore(i.date) && endDate.isAfter(i.date))
    .forEach(j -> Ranges.add(0, j));

Solution

  • You were almost there

     mainList.stream()
            .filter(i -> startDate.isBefore(i.date) && endDate.isAfter(i.date))
            .forEach(i -> {
                 //your code
                });