两个Java数组的对称差异 [英] Symmetric difference of two Java arrays

查看:94
本文介绍了两个Java数组的对称差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组

 String[] ID1={"19","20","12","13","14"};

 String[] ID2={"10","11","12","13","15"};  

在比较上面两个数组时,如何获得以下答案.

How can I get following answer while comparing above two arrays.

在比较上面两个数组时,我想排除共同的元素.

I want to exclude common elements while comparing above two arrays.

 String[] Result={"14","15","19","20","10","11"};

推荐答案

似乎您想将两个集合的并集(没有重复项,对吗?)减去交集:

Seems like you want the union of the two sets (no duplicates, right?) minus the intersection:

Set<Integer> union = new HashSet<Integer>(Arrays.asList(ID1));
union.addAll(Arrays.asList(ID2);

Set<Integer> intersection = new HashSet<Integer>(Arrays.asList(ID1));
intersection.retainAll(Arrays.asList(ID2);

union.removeAll(intersection);

// result is left in "union" (which is badly named now)

(我将您的String更改为Integer,这似乎更适合数据,但可以与String一起使用)

(I changed your String to Integer, which seems to fit the data better, but it would work with String the same way)

这篇关于两个Java数组的对称差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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