Symmetric difference of two Java arrays

前端 未结 2 389
抹茶落季
抹茶落季 2021-01-20 16:02

I have two arrays

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

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

How can I get

2条回答
  •  执念已碎
    2021-01-20 16:49

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

    Set union = new HashSet(Arrays.asList(ID1));
    union.addAll(Arrays.asList(ID2);
    
    Set intersection = new HashSet(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)

提交回复
热议问题