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

前端 未结 7 1149
甜味超标
甜味超标 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: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.

提交回复
热议问题