In this post, I will show a code snippet showing how to check if a String contains an element from an array in Java.
Java 8
If you can utilize Java 8, then follow the snippet below. In this snippet, we will use the Arrays API with Stream in parallel.
String[] items = {"po box", "P.O. Box"};
String address = "11627 Park St. po box 123, Ballico, CA, 95303";
boolean addressHasPOBox = Arrays.stream(items).parallel().anyMatch(address::contains);
System.out.println("The address has an item from the items array: " + addressHasPOBox);
Apache Commons
If you use StringUtils from Apache Commons
String[] items = {"po box", "P.O. Box"};
String address = "11627 Park St. po box 123, Ballico, CA, 95303";
boolean addressHasPOBox = StringUtils.indexOfAny(address, items);
System.out.println("The address has an item from the items array: " + addressHasPOBox);
Before than Java 8
If you cannot use Java 8, or Apache Commons, then we fallback to the classic and the most simple method to check if a String contains an element from an array:
String[] items = {"po box", "P.O. Box"};
String address = "11627 Park St. po box 123, Ballico, CA, 95303";
boolean addressHasPOBox = false;
for(String item: items) {
if(address.contains(item)) {
addressHasPOBox = true;
break;
}
}
System.out.println("The address has an item from the items array: " + addressHasPOBox);
0 Comments