我们如何从两个ArrayList中删除常用值.
让我们考虑我有两个Arraylist,如下所示
ArrayList1= [1,2,3,4]
ArrayList1= [2,3,4,6,7]
我希望得到结果
ArrayListFinal= [1,6,7]
有人可以帮帮我吗?
解决方法:
以下是完成任务后可以遵循的算法:
>构造两个数组的并集
>构造两个数组的交集
>从联合中减去交集以获得结果
Java集合支持addAll,removeAll和retainAll.使用addAll构造联合,使用retainAll构造交集,并使用removeAll进行减法,like this:
// Make the two lists
List list1 = Arrays.asList(1, 2, 3, 4);
List list2 = Arrays.asList(2, 3, 4, 6, 7);
// Prepare a union
List union = new ArrayList(list1);
union.addAll(list2);
// Prepare an intersection
List intersection = new ArrayList(list1);
intersection.retainAll(list2);
// Subtract the intersection from the union
union.removeAll(intersection);
// Print the result
for (Integer n : union) {
System.out.println(n);
}
标签:java,collections,list,arraylist
来源: https://codeday.me/bug/20190928/1827851.html