如何从两个数组列表中删除公用值 [英] How to remove common values from two array lists
本文介绍了如何从两个数组列表中删除公用值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从两个ArrayList中删除公用值?
How can we remove common values from two ArrayLists?
让我们考虑一下我有两个如下所示的Arraylist:
Let’s consider I have two Arraylist as shown below:
ArrayList1 = [1,2,3,4]
ArrayList1 = [2,3,4,6,7]
我希望得到的结果是:
ArrayListFinal = [1,6,7]
我该怎么办?
推荐答案
以下是您可以用来完成任务的算法:
Here is an algorithm that you could follow to accomplish the task:
- 构造两个数组的并集
- 构造两个数组的交集
- 从并集减去相交以获得结果
Java集合支持 retainAll
.使用addAll
构造并集,使用retainAll
构造相交,使用removeAll
进行相减,像这样:
Java collections support addAll
, removeAll
, and retainAll
. Use addAll
to construct unions, retainAll
for constructing intersections, and removeAll
for subtraction, like this:
// Make the two lists
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(2, 3, 4, 6, 7);
// Prepare a union
List<Integer> union = new ArrayList<Integer>(list1);
union.addAll(list2);
// Prepare an intersection
List<Integer> intersection = new ArrayList<Integer>(list1);
intersection.retainAll(list2);
// Subtract the intersection from the union
union.removeAll(intersection);
// Print the result
for (Integer n : union) {
System.out.println(n);
}
这篇关于如何从两个数组列表中删除公用值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文