如何从两个数组列表中删除公共值 [英] How to remove common values from two array lists

查看:26
本文介绍了如何从两个数组列表中删除公共值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何从两个 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 集合支持 addAllremoveAllretainAll.使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆