user1309197 user1309197 - 4 months ago 10
Java Question

Writing Java predicate to compare a list against another

I am trying to write a Java lambda expression with streams to do what the following code is doing. Given a List of Person and a List of DateFilter, remove any person from the persons list whose birthdate matches any of the dates within a range in the DateFilter list.

List<Person> people = getPerson();
List<DateFilter> dateFilters = getDateFilters();
List<Person> filteredPersons = new ArrayList<>();

for(Person p : people){
boolean isWithinRange = false;
for(int i = 0; i < dateFilters.size() && !isWithinRange; i++){
DateFilter dateFilter = dateFilters.get(i);
if(numOfDaysBetween(p.getBirthDate(),dateFilter.getDate()) < dateFilter.getDiffRange()){
isWithinRange = true;
}
}
if(!isWithinRange){
filteredPersons.add(p);
}
}


Is there a simplified way to do this ?

Thanks

Answer

Given your requirement :

Given a List of Person and a List of DateFilter, remove any person from the persons list whose birthdate matches any of the dates withing a range in the DateFilter list.

It sounds like mutability of your original people list is not a problem. Considering this, you can simplify your code with the removeIf function which also takes a Predicate and get rid of some boilerplate code + avoid the creation of a new List :

people.removeIf(person -> dateFilters.stream()
    .noneMatch(f -> numOfDaysBetween(person.getBirthDate(), f.getDate()) < f.getDiffRange()));

Then your people list will be cleaned from any Person that did not match the predicate.

Comments