如何检查一个 ArrayList 是否包含另一个 ArrayList 的任何元素? [英] How can I check if an ArrayList contains any element of another ArrayList?

查看:50
本文介绍了如何检查一个 ArrayList 是否包含另一个 ArrayList 的任何元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以判断一个ArrayList是否包含不同ArrayList的任何元素?

Is there any way to determine whether an ArrayList contains any element of a different ArrayList?

像这样:

list1.contains(any element of list2)

循环遍历list2的所有元素并逐个检查元素是唯一的方法吗?

Is looping through all the elements of list2 and checking the elements one by one the only way?

推荐答案

虽然效率不高,但很简洁并且使用了 API:

Although not highly efficient, this is terse and employs the API:

if (!new HashSet<T>(list1).retainAll(list2).isEmpty())
    // at least one element is shared 

这篇关于如何检查一个 ArrayList 是否包含另一个 ArrayList 的任何元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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