2

I'm trying to compare an object against a list of objects to know if this particular object is on the list, however there are some rules

  1. I don't want to override any existing methods
  2. I don't want to use custom comparators
  3. Solution should use already existing predicates

Code below:

List<String> PREDEFINED_CODES = Arrays.asList(PredefinedCodes.1, PredefinedCodes.2, PredefinedEventSetupCodes.3, PredefinedEventSetupCodes.4);

private BiPredicate<Event, String> isEventOfCode(){
    return (event, code) -> code.equals(event.getCode());
}

private Predicate<Event> isEvendPredefined(){
    return event -> PREDEFINED_CODES.stream().findAny(code -> isEventOfCode().test(event,code)).isPresent();
}

Note: This is simplified version of code to show my problem

Now the problem, I'm having this code -> isEventOfCode().test(event,code) in this lambda I can not test values against isEventOfCode predicate because Wrong 2nd argument type. Found: '<lambda parameter>', required: 'java.lang.String' although I know that PREDEFINED_CODES is a list of string, therefore code is of type String

Is there some workaround for calling the isEventOfCode() predicate with a parameter from lambda expression? I can not modify type of isEventOfCode() since its used in other parts of code.

2
  • 1
    But what advantage shall this BiPredicate<Event, String> returning method have? If you want to encapsulate the code.equals(event.getCode()) operation, you can use an ordinary method. Commented Jun 26, 2018 at 9:59
  • 1
    @Holger this is used in other parts of code to order some conditions and since logic for comparing these two values is in place, there is no point of creating dedicated method, also as stated in question this is simplified version of comparasion Commented Jun 26, 2018 at 10:09

1 Answer 1

4

findAny() takes no argument - so you typically use it on a stream that has a filter to check if there are any elements left after filtering. In your example, you would use:

return event -> PREDEFINED_CODES.stream().filter(code -> isEventOfCode().test(event,code))
                                         .findAny().isPresent();

But for your use case, it would make more sense to use anyMatch instead:

return event -> PREDEFINED_CODES.stream().anyMatch(code -> isEventOfCode().test(event,code));
Sign up to request clarification or add additional context in comments.

1 Comment

of course, this is correct answer. I have mixed up findAny() with anyMatch(). Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.