我有两个 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/