Finding the different elements between two ArrayLists in Java

后端 未结 6 1273
滥情空心
滥情空心 2021-02-06 05:43

How can I know the different element between 2 array list in java? I need the exact element not a Boolean value which can be retrieved using removeAll().

6条回答
  •  梦谈多话
    2021-02-06 06:15

    If I understood your question correctly then following method nonOverLap in the code below should get you that:

     Collection union(Collection coll1, Collection coll2) {
        Set union = new HashSet<>(coll1);
        union.addAll(new HashSet<>(coll2));
        return union;
    }
    
     Collection intersect(Collection coll1, Collection coll2) {
        Set intersection = new HashSet<>(coll1);
        intersection.retainAll(new HashSet<>(coll2));
        return intersection;
    }
    
     Collection nonOverLap(Collection coll1, Collection coll2) {
        Collection result = union(coll1, coll2);
        result.removeAll(intersect(coll1, coll2));
        return result;
    }
    

提交回复
热议问题