Create custom Predicate with Set<String> and String as parameter

房东的猫 提交于 2019-12-05 02:11:12

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;

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);
}

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

BiFunction<Set<String>,String,Boolean> checkIfCurrencyPresent = Set::contains;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!