[英]Convenient method to check if a list contains multiple elements
How can I check if a list of strings contains some specific strings at the same time, without having to do multiple contains. 如何检查字符串列表是否同时包含某些特定字符串,而不必执行多个包含。
For example something like this: 例如这样的事情:
if (templist.contains("aaa") && templist.contains("bbb")) {
}
List.containsAll
function can actually achieve your requirement. List.containsAll
函数实际上可以实现您的要求。 However, using containsAll
with list type can degrade in performance as the order is O(NK)
where N
is the number of elements of the list and K is the number of target string. 但是,使用containsAll
列表类型的containsAll
会降低性能,因为顺序为O(NK)
,其中N
是列表元素的数量,K是目标字符串的数量。 Try using a HashSet
to improve the performance: 尝试使用HashSet
来提高性能:
HashSet<String>set = new HashSet<>(list);
if(set.containsAll(Arrays.asList("asd", "efg")))
// do my job;
Because, HashSet<E>
class offers constant time performance for the basic operations ( add, remove, contains and size
). 因为, HashSet<E>
类为基本操作( add, remove, contains and size
)提供恒定的时间性能 。 As containsAll
inherently uses the contains
function to look up the element the order can be expected as O(N+K)
as containsAll
固有地使用contains
函数来查找元素,订单可以预期为O(N+K)
You can use containsAll
你可以使用containsAll
if (templist.containsAll(Arrays.asList("aaa", "bbb"))) {
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.