Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List filter by date

I try use my first filter in FilteredList but of course it doesn't work.

public class ListRemove {

    public static void main(String[] args) {

        ObservableList<CashBalance> cashBalanceList = FXCollections.observableArrayList();

        LocalDate f1 = LocalDate.of(2011, Month.JANUARY, 1);
        LocalDate f2 = LocalDate.of(2015, Month.AUGUST, 2);

        CashBalance c1 = new CashBalance();
        CashBalance c2 = new CashBalance();
        c1.setData(f1);
        c2.setData(f2);

        cashBalanceList.setAll(c1, c2);

        FilteredList<CashBalance> filteredList = new FilteredList<CashBalance>(cashBalanceList);

        filteredList.stream().filter(p -> p.getData().isAfter(LocalDate.of(2012, Month.JUNE, 2)))
                .collect(Collectors.toList());

        for (CashBalance l : filteredList) {

            System.out.println(l.getData());

        }
    }
}

Should show one date but two are displayed. What am I doing wrong ?

like image 588
Light Avatar asked Jan 02 '23 22:01

Light


2 Answers

Your approach does not filter the list, but copies the elements to a new list, with some elements filtered out. This leaves the original unchanged. You need to assign this new list to a variable to make use of it.

However, you are using the FilteredList class, which provides a filtered view of another list. You can set the filter predicate using the setPredicate method

filteredList.setPredicate(p -> p.getData().isAfter(LocalDate.of(2012, Month.JUNE, 2)));

Or in the constructor as the second parameter

 FilteredList<CashBalance> filteredList = new FilteredList<CashBalance>(cashBalanceList, p -> p.getData().isAfter(LocalDate.of(2012, Month.JUNE, 2)));
like image 167
puhlen Avatar answered Jan 05 '23 06:01

puhlen


change to:

filteredList = 
    filteredList
     .stream()
     .filter(
               p -> p.getData().isAfter(LocalDate.of(2012, Month.JUNE, 2))
    ).collect(Collectors.toList());
like image 36
Morteza Jalambadani Avatar answered Jan 05 '23 05:01

Morteza Jalambadani