【发布时间】:2015-01-15 08:56:31
【问题描述】:
如何检查字符串的ArrayList是否包含来自字符串数组的50个不同字符串中的每一个,以及ArrayList中每个相同的字符串是否要执行某些操作?
【问题讨论】:
-
你能告诉我们你做了什么吗?
-
我可以用双循环吗?
标签: android arrays string arraylist
如何检查字符串的ArrayList是否包含来自字符串数组的50个不同字符串中的每一个,以及ArrayList中每个相同的字符串是否要执行某些操作?
【问题讨论】:
标签: android arrays string arraylist
您可以使用此函数检查数组中的所有字符串是否也在 ArrayList 中。如果您想在每次找到匹配项时添加额外的逻辑,例如 doSomething(),您应该能够轻松地调整代码。
ArrayList myList; // let's assume its initialized and filled with Strings
String[] strArray; // let's assume its initialized and filled with Strings
//this function returns true if all Strings in the array are also in your arraylist
public boolean containsAll(myList, strArray){
//iterate your String array
for(int i = 0; i < strArray.length; i++){
if(!myList.contains(strArray[i])){
//String is not in arraylist, no need to check the rest of the Strings
return false;
}
}
return true;
}
【讨论】:
为什么不使用 LINQ?
List<String> duplicates = YourList.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
请注意,这将在新的 List<string> 中返回所有重复项,因此如果您只想知道源列表中重复的项目,您可以将 Distinct 应用于结果序列或使用上面给出的解决方案
【讨论】: