Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 685
Ishant Gaurav Avatar asked Jan 04 '19 14:01

Ishant Gaurav


People also ask

What is predicate string in Java?

The predicate is a predefined functional interface in Java defined in the java. util. Function package. It helps with manageability of code, aids in unit-testing, and provides various handy functions.

What is BiPredicate?

Interface BiPredicate<T,U>Represents a predicate (boolean-valued function) of two arguments. This is the two-arity specialization of Predicate . This is a functional interface whose functional method is test(Object, Object) .

What is the difference between a predicate integer and an IntPredicate?

Java IntPredicate interface is a predicate of one int-valued argument. It can be considered an operator or function that returns a value either true or false based on certain evaluation on the argument int value. IntPredicate is a functional interface whose functional method is boolean test(int a) .


2 Answers

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;
like image 149
Ousmane D. Avatar answered Sep 17 '22 19:09

Ousmane D.


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);
}
like image 22
Naman Avatar answered Sep 17 '22 19:09

Naman