Verify that any object in the ArrayList satisfies a condition

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

Instead of looping through a list, is there a better way to accomplish this? Maybe some kind of mapping or lambda way?

Edit:

Hi and thanks for the answers!

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

+4
source share
4 answers

I am not familiar with Guava, but you still β€œloop the list” with Iterables.any . If your Person state never changes while in the list, than use your own subclass ArrayList (or another impl list) and check the condition in the insert methods.

+1
source

I would recommend Guava (formally Google Collections), specifically Iterables.any , to check if one instance matches one condition, or Iterables.all to check if all instances match the conditions. You can establish that your predicate either matches some logical expression or checks that all elements are equal to the head of the list.

It does nothing interesting under the hood, but at least you get the habit of writing code in a functional style.

+4
source

You can use Guava :

 List<Person> persons = ...; List<Person> matchingUsers = Collections2.filter(persons, new Predicate<Person>() { @Override public boolean apply(Person person) { return person.isFemale(); } }); if (!matchingUsers.isEmpty()) { ... } 
+3
source

Why do you need to loop around the list to find out something about the Person instance - if you have a reference to Person, just use this. I can only assume that you had in mind the question:

How to find Person instances that match a specific condition?

If so, you can sort the list using a comparator that sorts the identity with isFemale () at a low level, so they go to the top of the list, then you can loop until person.isFemale () is false, for example:

 List<Person> persons = ...; Collections.sort(list, new Comparator<Person>() { public int compare(Person o1, Person o2) { return o1.isFemale().compareTo(o2.isFemale()); // Note: Assumes isFemale returns Boolean, not boolean. Otherwise, wrap before comparing. } }); for (Person person : persons) { if (!person.isFemale()) { break; } // Do something with females } 

Note. This is not a good idea, because it will be slower than just moving the list in the usual way, however I tried to answer the question as indicated.

+1
source

All Articles