Symmetric difference of two Java arrays

不羁的心 提交于 2019-12-31 02:18:30

问题


I have two arrays

 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"};

回答1:


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)

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




回答2:


It looks like XOR operation ;)

Please describe your needs a little bit more directly. Pseudocode:

foreach s in ID1 {
  if(ID2.contains(s)) {
    ID2.remove(s)
  } else {
    ID2.add(s)
  }
}

ID2 will contain your result. In assumption that there are not duplicates in both arrays.



来源:https://stackoverflow.com/questions/13762164/symmetric-difference-of-two-java-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!