[英]How to check if two String values from an Arraylist are contained in another Arraylist?
I have an Arraylist that contains two String values, and I want to check if these values are both present in the second Arraylist. 我有一个包含两个String值的Arraylist,我想检查这些值是否都存在于第二个Arraylist中。 For some reason, I am stuck, and I can't get my code to work. 出于某种原因,我陷入困境,我无法让我的代码工作。
Here is my code: 这是我的代码:
public static void main(String[] args) {
ArrayList <String> list1 = new ArrayList <String>();
list1.add("bob");
list1.add("karen");
ArrayList <String> list2 = new ArrayList <String>();
list2.add("java");
list2.add("karen");
list2.add("cook");
list2.add("tablet");
list2.add("cup");
list2.add("coffee");
for (String list11 : list1) {
for (String list22 : list2) {
if (list22.contains(list11)){
System.out.println ("List 2 contains the strings from list1");
}
}
}
}
My if statement is being executed even though all the values from list11 do not exist in list22, but only one of them. 我的if语句正在执行,即使list11中的所有值都不存在于list22中,但只有其中一个。 My goal is to execute the if statement only when all the values in list1 are present in list2, without hardcoding anything because list1 is supposed to grow in size eventually. 我的目标是只有当list1中的所有值都出现在list2中时才执行if语句,而不需要硬编码任何东西,因为list1最终应该增大。
What am I doing wrong? 我究竟做错了什么?
Use this: 用这个:
if(list2.containsAll(list1))
System.out.println ("List 2 contains the strings from list1");
.containsAll()
returns true
if all objects in the specified collection (list1) are elements of this List (list2) , & false
otherwise. 如果指定集合(list1)中的所有对象都是此List (list2)的元素,则.containsAll()
将返回true
否则返回false
。
As in your case list2
is superset of list1
which you are checking, the for loop should look like: 在你的情况下, list2
是你正在检查的list1
超集,for循环应该如下所示:
boolean allElementsPresent = true;
for (String list11 : list1) {
if (!list22.contains(list11)){
allElementsPresent = false;
}
}
if(allElementsPresent){
System.out.println ("List 2 contains the strings from list1");
}
There is no need to iterate over list2
objects. 无需迭代list2
对象。 You only need to iterate over list1
to check if each and every element exists in list2
or not. 您只需要遍历list1
以检查list2
是否存在每个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.