Reputation: 169
I have an Arraylist that contains two String values, and I want to check if these values are both present in the second 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. 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.
What am I doing wrong?
Upvotes: 1
Views: 833
Reputation: 17142
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.
Upvotes: 2
Reputation: 824
As in your case list2
is superset of list1
which you are checking, the for loop should look like:
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. You only need to iterate over list1
to check if each and every element exists in list2
or not.
Upvotes: 1