سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top