如何从两个数组列表中删除常用值

Gau*_*tam 16 java collections list arraylist

我们如何从两个ArrayList中删除常用值.让我们考虑我有两个Arraylist,如下所示

ArrayList1= [1,2,3,4]
ArrayList1= [2,3,4,6,7]
Run Code Online (Sandbox Code Playgroud)

我希望得到结果

ArrayListFinal= [1,6,7]
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?

das*_*ght 40

以下是完成任务后可以遵循的算法:

  • 构造两个数组的并集
  • 构造两个数组的交集
  • 从联合中减去交集以获得结果

Java集合支持addAll,removeAllretainAll.使用addAll构建工会,retainAll构建交叉,并removeAll作减法,像这样的:

// 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);
}
Run Code Online (Sandbox Code Playgroud)


Old*_*eon 18

你实际上是在要求对称差异.

List<Integer> aList = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> bList = new ArrayList<>(Arrays.asList(2, 3, 4, 6, 7));
// Union is all from both lists.
List<Integer> union = new ArrayList(aList);
union.addAll(bList);
// Intersection is only those in both.
List<Integer> intersection = new ArrayList(aList);
intersection.retainAll(bList);
// Symmetric difference is all except those in both.    
List<Integer> symmetricDifference = new ArrayList(union);
symmetricDifference.removeAll(intersection);

System.out.println("aList: " + aList);
System.out.println("bList: " + bList);
System.out.println("union: " + union);
System.out.println("intersection: " + intersection);
System.out.println("**symmetricDifference: " + symmetricDifference+"**");
Run Code Online (Sandbox Code Playgroud)

打印:

aList: [1, 2, 3, 4]
bList: [2, 3, 4, 6, 7]
union: [1, 2, 3, 4, 2, 3, 4, 6, 7]
intersection: [2, 3, 4]
**symmetricDifference: [1, 6, 7]**
Run Code Online (Sandbox Code Playgroud)