Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, can I make a predicate that applies a filter on more than one object?

I have a predicate that I use to filter a list of the same Entity Object:

Predicate<DWHDeal> companyFilter = i -> i.getCompany().equals(company);

I also have to apply the same filter, with the exact same condition on the exact same field, on a list of DTOs where the DTOS is built based on the entity from before:

Predicate<DWHDealDTO> companyFilterDTO = i -> i.getCompany().equals(company);

Is it possible to achieve this without instancing two different predicates? If possible, I would like to achieve this by making only one Predicate.

like image 634
R.S. Avatar asked Mar 03 '20 08:03

R.S.


1 Answers

Assuming getCompany() returns a String you could create Predicate<String>:

Predicate<String> predicate = s -> s.equals(company);

And then using it like:

list.stream()
    .filter(dto -> predicate.test(dto.getCompany()))
    ...

But there is not much benefit since it requires almost the same code.

like image 182
Ruslan Avatar answered Nov 16 '22 16:11

Ruslan