[英]Checking to see if a list<string> contains text from another list<string>
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 [Ex] 想要验证字符串“Application Scan”是否存在于 list2 中“This is an example sentence that has Application Scan in it”的文本中
List list1 = new ArrayList();列表 list1 = new ArrayList(); List list2 = new ArrayList();列表 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到目前为止,我的方法一直说在 list2 中找不到 list1 内容,我不确定如何准确解决这个问题
If you are using Java 8 you can use:如果您使用的是 Java 8,您可以使用:
if (list2.stream().anyMatch(l -> list1.stream().anyMatch(l::contains))) {
Which mean, to check each element in list2 can contain any element in list1这意味着,要检查 list2 中的每个元素可以包含 list1 中的任何元素
You will have to iterate both lists.您将不得不迭代这两个列表。 Since the list2 contains the big texts, the outer loop will be for list2:由于 list2 包含大文本,因此外部循环将用于 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.