Search code examples
javaarrayslistobjectlocaldate

How to filter an array of objects by month and year - Java


I'm new at Java and I have a question. I have this array of objects:

List<Expense> expenses = er.findAll();

That contains this:

enter image description here

I would like to know how can I filter this array by month and year.

A first example would be filter the array by month 10 and year 2021.

Any suggestion ?


Solution

  • You can use the Stream API to do it as follows:

    List<Expense> result = 
        expenses.stream()
                .filter(e -> e.getDate().getMonthValue() ==  10 && e.getDate().getYear() ==  2021)
                .collect(Collectors.toList());
    

    Alternatively,

    List<Expense> result = 
        expenses.stream()
                .filter(e -> {
                    LocalDate date = e.getDate();
                    return date.getMonthValue()  ==  10 && date.getYear() ==  2021;
                })
                .collect(Collectors.toList());
    

    I recommend you do it in the second way to avoid Expense#getDate getting called twice in each step.