1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I liked your answer more. Good to make your own "logic" instead of using Spartas solution since I am a junior. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.