【问题标题】:Check if ArrayList of Strings contains 50 different Strings one by one检查 ArrayList of Strings 是否一一包含 50 个不同的字符串
【发布时间】:2015-01-15 08:56:31
【问题描述】:

如何检查字符串的ArrayList是否包含来自字符串数组的50个不同字符串中的每一个,以及ArrayList中每个相同的字符串是否要执行某些操作?

【问题讨论】:

  • 你能告诉我们你做了什么吗?
  • 我可以用双循环吗?

标签: android arrays string arraylist


【解决方案1】:

您可以使用此函数检查数组中的所有字符串是否也在 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; 
}

【讨论】:

  • 谢谢,这正是我需要的
【解决方案2】:

为什么不使用 LINQ?

    List<String> duplicates = YourList.GroupBy(x => x)
                         .Where(g => g.Count() > 1)
                         .Select(g => g.Key)
                         .ToList();

请注意,这将在新的 List&lt;string&gt; 中返回所有重复项,因此如果您只想知道源列表中重复的项目,您可以将 Distinct 应用于结果序列或使用上面给出的解决方案

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 2011-09-19
    • 2013-03-13
    • 2021-11-10
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    相关资源
    最近更新 更多