簡體   English   中英

檢查 ArrayList 是否包含來自另一個 ArrayList(或 Collection)的每個元素

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

可能有一個簡單的單線我在這里找不到,但這是我的問題:

如何檢查一個 ArrayList 是否包含另一個 ArrayList 中的所有對象? 我正在尋找(如果存在)以下內容:

//INCORRECT EXAMPLE:
if(one.contains(two))
{
    return true;
}
else
{
    return false;
}

例如:

ArrayList one = {1, 2, 3, 4, 5}

ArrayList two = {1, 2, 3} --> True
ArrayList two = {} --> True
ArrayList two = {1, 2, 3, 4, 5} --> True
ArrayList two = {1, 5, 2} --> True
ArrayList two = {1, 7, 4} --> False
ArrayList two = {0, 1, 3} --> False
ArrayList two = {4, 5, 6} --> False
ArrayList two = {7, 8, 9} --> False

java.util.Collection接口containsAll聲明了一個名為containsAll的方法。 在您的設置中one.containsAll(two)給出了所需的答案。

根據列表界面:

myList.containsAll(...);

查看List接口中的containsAll(Collection<?> c)方法。 我認為這就是你要找的。

這是我在 JUnit 測試中用於斷言兩個數組相等的 containsAll() 的另一個使用示例:

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));

您可以使用列表的containsAll方法進行檢查。 然而,這是一個線性操作。 如果列表很大,則應先將其轉換為HashSet ,然后執行containsAll

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

如果長度oneN和兩種是長度M ,該解決方案具有時間的復雜性O(M+N) ; “普通” containsAll具有O(M*N)的復雜性,這可能會更糟。

您在示例中的代碼沒有意義,但無論如何這里有一個示例。

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;
    }
}

它只是循環遍歷所有two元素並檢查它們是否在one

然后 boolean good包含您想要的值。

請參閱ArrayList#contains

編輯:哦,哇,我完全忘記了containsAll 哦,好吧,如果您真的想了解它,這是另一種方法。

這也可以使用 Java 中的流來完成

    List<String> employeeList = Arrays.asList("Marc","john");
    List<String> masterEmployeeList = Arrays.asList("Marc", "Stacy", "john");
    System.out.println(employeeList.stream().allMatch(masterEmployeeList::contains));

在 org.apache.commons.collections.CollectionUtils 中聲明的 isEqualCollection() 方法為您提供相同或不同的集合。

if (CollectionUtils.isEqualCollection(collectionA,collectionB)) { do smt... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM