在 Java 中查找两个 ArrayList 之间的不同元素 [英] Finding the different elements between two ArrayLists in Java

查看:28
本文介绍了在 Java 中查找两个 ArrayList 之间的不同元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何知道java中2个数组列表之间的不同元素?我需要确切的元素而不是可以使用 removeAll() 检索的布尔值.

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().

推荐答案

如果我正确理解了你的问题,那么下面代码中的方法 nonOverLap 应该会让你:

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

<T> Collection<T> union(Collection<T> coll1, Collection<T> coll2) {
    Set<T> union = new HashSet<>(coll1);
    union.addAll(new HashSet<>(coll2));
    return union;
}

<T> Collection<T> intersect(Collection<T> coll1, Collection<T> coll2) {
    Set<T> intersection = new HashSet<>(coll1);
    intersection.retainAll(new HashSet<>(coll2));
    return intersection;
}

<T> Collection<T> nonOverLap(Collection<T> coll1, Collection<T> coll2) {
    Collection<T> result = union(coll1, coll2);
    result.removeAll(intersect(coll1, coll2));
    return result;
}

这篇关于在 Java 中查找两个 ArrayList 之间的不同元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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