In this article, we will learn how to search a list of keywords/strings in a String/ Text using Java 8 stream API.
We have an input string, in which we want to search a list of keywords –
String inout = "We love to code in Java8 and Python";
And we also have a list of keywords listed below –
List <String> list = new ArrayList();
list.add("xml");
list.add("XSLT");
list.add("html");
list.add("python");
list.add("java");
list.add("java8");
list.add("ruby");
list.add("rails");
Now below code using Java8 will search for all the keywords available in the input text and return those matched keywords.
@Slf4j
public class CommonUtility {
public static List<String> checkIfListWordMatches(final String inputText, List<String> keywords){
List<String> matchingResult = keywords.stream()
.filter(s -> inputText.matches(".*\\b"+s.toLowerCase()+"\\b.*"))
.collect(Collectors.toList());
return matchingResult;
}
public static void main(String[] args) {
String string="We love to code in Java8 and Python";
List <String> list = new ArrayList();
list.add("XML");
list.add("xslt");
list.add("html");
list.add("java");
list.add("java8");
list.add("Python");
list.add("Ruby");
list.add("Go");
List<String> result = checkIfListWordMatches(string.toLowerCase(), list);
log.info(result.toString());
}
}
We have used filter() and collect() of the Java Stream API in the above case. The result will the list of keywords found in the input string (if any) or an empty list. Before doing the matching we converted the input string and the values in the list in lower case to handle case insensitive.
Output:
[java8, Python]
Jkoder.com Tutorials, Tips and interview questions for Java, J2EE, Android, Spring, Hibernate, Javascript and other languages for software developers