Searching for a String in Java 8
Java 8 introduced a lot of functional programming features and one of them is the stream() method which allows us to manipulate collections in a functional way. In this article, we’ll see how we can use the stream() method and the anyMatch() method to search for a string in a list of strings and return true if any of the strings in the list are present in the source string.
First, let's write the method to do the search:
import java.util.List;
public class Main {
public static boolean containsString(String source, List targets) {
return targets.stream().anyMatch(target -> source.contains(target));
}
}
The containsString() method takes two arguments: source which is the string that we want to search in, and targets which is the list of strings that we want to search for. The method returns a boolean value indicating whether any of the strings in the list are present in the source string.
To use the containsString() method, we need to call it and pass in the source string and the targets list:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
String source = "This is a sample string";
List targets = Arrays.asList("sample", "string");
boolean result = containsString(source, targets);
System.out.println(result); // output: true
}
}
In the example above, we create a source string and a targets list, and then we call the containsString() method to search for any of the strings in the list in the source string. The output of the code is true which means that at least one of the strings in the list is present in the source string.
In conclusion, we saw how we can use the stream() method and the anyMatch() method to search for a string in a list of strings in Java 8. This is a very concise and efficient way to search for strings in collections.
Comments
Post a Comment