HellishHeat
HellishHeat

Reputation: 2491

Can I pass an arg to a custom Lambdaj Predicate?

Is it possible to pass an argument to a lambdaj Predicate?

public static Matcher<SomeObject> isSpecialObject = new Predicate<SomeObject>() {
        public boolean apply(SomeObject specialObj) {
            return LIST_OF_SPECIAL_IDS.contains(specialObj.getTypeId());
        }
    };

I would like to alter the above predicate so I can pass in a list, rather than use the static list LIST_OF_SPECIAL_IDS. Is that possible?

Thanks.

Upvotes: 1

Views: 375

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500185

I suspect you want something like:

public static Matcher<SomeObject> createPredicate(final List<String> ids) {
    return new Predicate<SomeObject>() {
        public boolean apply(SomeObject specialObj) {
            return ids.contains(specialObj.getTypeId());
        }
    };
}

You've got to make it a method rather than just a field, as otherwise you've got nowhere to pass the list. The parameter has to be final so that you can use it within the anonymous inner class.

Upvotes: 4

Related Questions