nehacharya
nehacharya

Reputation: 957

How to filter a String date range from an arrayList using filter() in Java?

I am trying to filter records from a List<People> based on date range which are stored as Strings.

List (showing 3 entries only):

[["Steve","Baseball","Brazil","August 14, 2020"], ["Ammie","Basketball","Malaysia","September 8, 2021"], ["Tom","Cricket","UK","December 1, 2020"]]

How can I filter all records between startDate (String): August 14, 2020 to endDate (String): September 8, 2020?

Currently I am doing this but it's not getting the range values. It only matches either the start date or the end date which isn't what I want.

return people.stream().filter(t -> {
       return t.getType().equals(type) && 
           (t.getDateAdded().equals(startDate) ||
                 t.getDateAdded().equals(endDate));
       }
).limit(numberOfRecords).collect(Collectors.toList());

Any help will be greatly appreciated. Thank you!

Upvotes: 1

Views: 889

Answers (1)

Andreas
Andreas

Reputation: 159135

Why is the dateAdded property of People a type String? Change that to a LocalDate.

Change startDate and endDate to LocalDate too.

Then do:

filter(t -> t.getType().equals(type)
         && t.getDateAdded().compareTo(startDate) >= 0
         && t.getDateAdded().compareTo(endDate) <= 0)

Upvotes: 3

Related Questions