Wednesday, 2 October 2019

Java 8 predicate test method example

for this
https://stackoverflow.com/questions/1128723/how-do-i-determine-whether-an-array-contains-a-particular-value-in-java/1128728#1128728                 

I have a String[] with values like so:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
Given String s, is there a good way of testing whether VALUES contains s?
ANS:
Java 8 predicate test method is best for it.
test(T t) : Evaluates this predicate on the given argument.boolean test(T t)
test(T t) Parameters: t - the input argument Returns: true if the input argument matches the predicate, otherwise false
Here is a full example of it.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Test {

public static final List<String> VALUES = Arrays.asList("AA", "AB", "BC", "CD", "AE");

public static void main(String args[]) {

Predicate<String> containsLetterA = VALUES -> VALUES.contains("AB");
for (String i : VALUES) {
System.out.println(containsLetterA.test(i));
}
}

}


No comments:

Post a Comment