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

Time:10-05

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 ?

CodePudding user response:

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.

CodePudding user response:

//You could use foreach.

int monthNumb = 10;
for(expense ex : expenses)
if(ex.date == monthNumb) { /*behavior*/}

CodePudding user response:

Alternative to @Avinds correct answer, I would suggest using java.time.YearMonth to make it obvious what is filterd:

YearMonth ymFilter = YearMonth.of(2021,10);

List<Expense> result = expenses.stream()
                               .filter(ex -> YearMonth.from(ex.getDate()).equals(ymFilter))
                               .collect(Collectors.toList());
  • Related