Check if an ArrayList contains every element from another ArrayList (or Collection)

前端 未结 7 1099
甜味超标
甜味超标 2020-11-28 10:12

There is probably a simple one-liner that I am just not finding here, but this is my question:

How do I check if an ArrayList contains all of the objects in another

相关标签:
7条回答
  • 2020-11-28 10:41

    Per the List interface:

    myList.containsAll(...);
    
    0 讨论(0)
  • 2020-11-28 10:46

    You can use containsAll method of the list to do the check. However, this is a linear operation. If the list is large, you should convert it to HashSet first, and then perform containsAll:

    HashSet tmp = new HashSet(one);
    if (tmp.containsAll(two)) {
        ...
    }
    

    If the length of one is N and the length of two is M, this solution has time complexity of O(M+N); the "plain" containsAll has the complexity of O(M*N), which may be significantly worse.

    0 讨论(0)
  • 2020-11-28 10:51

    Here is another example use of containsAll() that I have used for asserting that two arrays are equal in JUnit testing:

    List<String> expected = new ArrayList<String>();
    expected.add("this");
    expected.add("that");
    expected.add("another");
    
    List<String> actual = new ArrayListString();
    actual.add("another");
    actual.add("that");
    actual.add("this");
    
    Assert.assertTrue("The lists do not match!", expected.containsAll(actual));
    
    0 讨论(0)
  • 2020-11-28 10:55

    Take a look at containsAll(Collection<?> c) method from List interface. I think it is what you are looking for.

    0 讨论(0)
  • 2020-11-28 10:57

    There is a method called containsAll declared in the java.util.Collection interface. In your setting one.containsAll(two) gives the desired answer.

    0 讨论(0)
  • 2020-11-28 10:59

    Your code in the example doesn't make sense, but here's an example anyway.

    ArrayList<Integer> one, two;
    //initialize
    boolean good = true;
    for (int i = 0; i < two.size(); i ++) {
        if (!(one.contains(two.get(i))) {
            good = false;
            break;
        }
    }
    

    It simply loops through all of two's elements and checks to see if they are in one.

    Then the boolean good contains the value you want.

    See ArrayList#contains.

    EDIT: oh wow, I totally forgot containsAll. Oh well, this is an alternate way to do it if you really want to understand it.

    0 讨论(0)
提交回复
热议问题