gpt4 book ai didi

java - 如何计算两个 ArrayList 之间的差异?

转载 作者:IT老高 更新时间:2023-10-28 11:45:09 29 4
gpt4 key购买 nike

我有两个 ArrayList。

ArrayList A 包含:

['2009-05-18','2009-05-19','2009-05-21']

ArrayList B 包含:

['2009-05-18','2009-05-18','2009-05-19','2009-05-19','2009-05-20','2009-05-21','2009-05-21','2009-05-22']

我必须比较 ArrayList A 和 ArrayList B。结果 ArrayList 应该包含 ArrayList A 中不存在的 List。

ArrayList 结果应该是:

['2009-05-20','2009-05-22']

如何比较?

最佳答案

在 Java 中,您可以使用 Collection接口(interface)的removeAll方法。

// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
add("apple");
add("orange");
}};

Collection secondList = new ArrayList() {{
add("apple");
add("orange");
add("banana");
add("strawberry");
}};

// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);

// Remove all elements in firstList from secondList
secondList.removeAll(firstList);

// Show the "after" list
System.out.println("Result: " + secondList);

上面的代码会产生如下输出:

First List: [apple, orange]
Second List: [apple, orange, banana, strawberry]
Result: [banana, strawberry]

关于java - 如何计算两个 ArrayList 之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/919387/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com