Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if some object in ArrayList fulfills some condition

I have an ArrayList<Person> persons. I want to check if some person in persons fulfills a condition. Like: person.isFemale()

Instead of looping the list, is there any nicer way to perform this? Some mapping or lambda way maybe?

Edit:

Hello and thanks for the replies!

I think I asked the wrong question.. I want to check if any object in the list differ from any other: boolean different = (if isMale() && isFemale()) somewhere in the list.

like image 485
Filip Avatar asked Jan 20 '23 05:01

Filip


1 Answers

I would recommend Guava (formally Google Collections), specifically Iterables.any to test if a single instance matches a condition or Iterables.all to test if all instances match a condition. You can set your predicate to either match some logical expression or test all elements are equal to the head of the list.

This isn't doing anything fancy under the hood, but it does at least get you into the habit of writing code in the functional style.

like image 140
Jon Freedman Avatar answered Jan 30 '23 21:01

Jon Freedman