Reputation: 375
I have two different list. One contains only service titles, and the other contains long sentences with the service titles in the text. I'm interested in finding a way to determining if the titles from one list are present within the long sentences of the other list. I'm not looking for whether these two list are an exact match. Only if one of them contains the contents of the other.
[Ex] Want to verify that the string "Application Scan" is present within the text in "This is an example sentence that has Application Scan in it" in list2
List list1 = new ArrayList(); List list2 = new ArrayList();
list1.add("Application Scan");
list1.add("Antivirus and HIPS");
list1.add("Backup Administration");
list2.add("This is an example sentence that has Application Scan in it");
list2.add("This is an example sentence that has Antivirus and HIPS in it");
list2.add("This is an example sentence that has Backup Administration in it");
if (list2.containsAll(list1)) {
System.out.print("Yes, list1 contents are in list2");
}
else {
System.out.println("No, list1 contents are not within list2");
}
My approach so far keeps saying that the list1 contents are not found within list2 and I'm not sure how to fix this exactly
Upvotes: 0
Views: 852
Reputation: 6818
You will have to iterate both lists. Since the list2 contains the big texts, the outer loop will be for list2:
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add("Application Scan");
list1.add("Antivirus and HIPS");
list1.add("Backup Administration");
List<String> list2 = new ArrayList<>();
list2.add("This is an example sentence that has Application Scan in it");
list2.add("This is an example sentence that has Antivirus and HIPS in it");
list2.add("This is an example sentence that has Backup Administration in it");
list2.forEach(bigtext -> {
list1.forEach(service -> {
if (bigtext.contains(service)) {
System.out.println(service);
}
});
});
}
prints:
Application Scan
Antivirus and HIPS
Backup Administration
It is the same with doing this:
for (String bigText : list2) {
for (String service : list1) {
if (bigText.contains(service))
System.out.println(service);
}
}
Upvotes: 2
Reputation: 60046
If you are using Java 8 you can use :
if (list2.stream().anyMatch(l -> list1.stream().anyMatch(l::contains))) {
Which mean, to check each element in list2 can contain any element in list1
Upvotes: 1