allMatch, anyMatch and noneMatch methods introduced in Java 8 can be used with Lambda Expressions to find if any word or letter exists in a list of strings or not.
Kindly check the below code to see the behavior of the 3 methods.
import java.util.*;
import java.util.stream.*;
public class Java8MatchExample {
public static void main(String args[]) {
List<String> namesList = Java8MatchExample.getNamesList();
boolean respMatch = namesList.stream().allMatch(n->n.contains("z"));
if(respMatch==true){
System.out.println("All words contain z");
}
else{
System.out.println("Not all words contain z");
}
boolean respAnyMatch = namesList.stream().anyMatch(n->n.contains("z"));
if(respAnyMatch==true){
System.out.println("Atleast one word contains z");
}
else{
System.out.println("None of the words contain z");
}
boolean respNoneMatch = namesList.stream().noneMatch(n->n.contains("y"));
if(respNoneMatch==true){
System.out.println("None of the words contains y");
}
else{
System.out.println("One or more words contain y");
}
}
private static List<String> getNamesList(){
List<String> list = new ArrayList<String>();
list.add("nathan");
list.add("chris");
list.add("david");
list.add("james");
list.add("mike");
list.add("zack");
return list;
}
}
