9

I have a String as "ishant" and a Set<String> as ["Ishant", "Gaurav", "sdnj"] . I need to write the Predicate for this. I have tried as below code, but it is not working

Predicate<Set<String>,String> checkIfCurrencyPresent = (currencyList,currency) -> currencyList.contains(currency);

How can I create a Predicate which will take Set<String> and String as a parameter and can give the result?

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Ishant Gaurav
  • 1,183
  • 2
  • 13
  • 32

3 Answers3

9

A Predicate<T> which you're currently using represents a predicate (boolean-valued function) of one argument.

You're looking for a BiPredicate<T,U> which essentially represents a predicate (boolean-valued function) of two arguments.

BiPredicate<Set<String>,String>  checkIfCurrencyPresent = (set,currency) -> set.contains(currency);

or with method reference:

BiPredicate<Set<String>,String> checkIfCurrencyPresent = Set::contains;
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • How to call this predicate within in the code? I am using this code boolean isCurrencyCodeValid = requestCurrencyCodes.stream() .noneMatch(checkIfCurrencyPresent(currencyValues,requireCurreny)); – Ishant Gaurav Jan 05 '19 at 03:23
7

If you were to stick with using Predicate, use something similar as :

Set<String> currencies = Set.of("Ishant", "Gaurav", "sdnj");
String input = "ishant";
Predicate<String> predicate = currencies::contains;
System.out.print(predicate.test(input)); // prints false

The primary difference between the BiPredicate and Predicate would be their test method implementation. A Predicate would use

public boolean test(String o) {
    return currencies.contains(o);
}

and a BiPredicate would instead use

public boolean test(Set<String> set, String currency) {
    return set.contains(currency);
}
Naman
  • 27,789
  • 26
  • 218
  • 353
2

Aomine's answer is complete. using of BiFunction<T, U, R> is another way:

BiFunction<Set<String>,String,Boolean> checkIfCurrencyPresent = Set::contains;
Hadi J
  • 16,989
  • 4
  • 36
  • 62