如何从两个数组列表中删除共同的价值观 [英] How to remove common values from two array list

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

问题描述

如何可以从两个ArrayList中删除共同的价值观。
让我们考虑我有两个数组列表如下图所示。

How can we remove common values from two ArrayList. lets consider i have two Arraylist as shown below

ArrayList1 = [1,2,3,4]
ArrayList1 = [2,3,4,6,7]

ArrayList1= [1,2,3,4] ArrayList1= [2,3,4,6,7]

我想有结果作为ArrayListFinal = [1,6,7]

I would like to have result as ArrayListFinal= [1,6,7]

任何人都可以请帮我。

由于提前

推荐答案

下面是你可以按照完成任务的算法:

Here is an algorithm that you could follow to accomplish the task:


  • 构建两个数组的联合

  • 构造两个数组的交集

  • 从工会减去路口,让您的结果

Java集合支持<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#addAll%28java.util.Collection%29\"><$c$c>addAll, <一href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#removeAll%28java.util.Collection%29\"><$c$c>removeAll,和<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#retainAll%28java.util.Collection%29\"><$c$c>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屋!

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