开发者

Check if some object in ArrayList fulfills some condition

开发者 https://www.devze.com 2023-03-21 00:56 出处:网络
I have an ArrayList<Person> persons.I want to check if some person in persons fulfills a condition. Like: person.isFemale开发者_开发知识库()

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.


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.


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()) {
    ...
}


I'm not familiar with Guava, but you would "looping the list" with Iterables.any anyway. If your condition of your Person never change while being in the list, than use a custom subclass of ArrayList (or other list impl) and check the condition in the insertion methods.


Why would you "loop the list" to find out something about a Person instance - if you have a reference to the Person, simply use that. I can only assume that you meant the question to say:

How do I find Person instances that match a certain condition?

If so, you could sort the list using a Comparator that sorts Persons with isFemale() low, so they go to the head of the List, then you could loop until person.isFemale() was false, like this:

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 isn't a good idea, because it's going to be slower than just traversing the list in the usual way, however I was trying to answer the question as stated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号