检查字符串是否存在于ArrayList中。

huangapple go评论72阅读模式
英文:

Check if string exists in ArrayList

问题

我有一个包含不同游戏类型的ArrayList:

List<String> availableGenres = new ArrayList<>(Arrays.asList("Arcade", "Puzzle", "Racing", "Casual", 
      "Strategy", "Sport"));

我想要检查传入的字符串是否存在于这个ArrayList中。使用contains方法是简单的,比如传入"Sport":

if (availableGenres.contains(game.getGenre())){
    ...    
    这是真的   
}

但有时候传入的字符串包含了这些值中的多个,比如:"Puzzle Arcade",而这个方法会返回false,但实际上是true。如何处理这种情况呢?

英文:

I have an ArrayList with genres:

List&lt;String&gt; availableGenres = new ArrayList&lt;&gt;(Arrays.asList(&quot;Arcade&quot;, &quot;Puzzle&quot;, &quot;Racing&quot;, &quot;Casual&quot;, 
      &quot;Strategy&quot;, &quot;Sport&quot;)
        );

I want to check if incoming string exists in this ArrayList. Okay, it's simple with contains, incoming "Sport":

if (availableGenres.contains(game.getGenre())){
    ...    
    this true   
}

But sometimes incoming String contains both of these values, like this: "Puzzle Arcade" and this method will return false, but it's actually true. How to deal with this case?

答案1

得分: 2

你可以做的是使用空白字符拆分输入,然后检查ArrayList中的任何值是否包含任何输入值。

String input = "Puzzle Arcade";

boolean contains = Stream.of(input.split(" "))
    .anyMatch(availableGenres::contains);

值得注意的是,如果值是唯一的(包括区分大小写),你也可以使用字符串的集合(Set)而不是列表(List)。

英文:

What you can do is split the input using whitespace and then check if any of the values in the ArrayList contain any of the input value(s).

String input = &quot;Puzzle Arcade&quot;;

boolean contains = Stream.of(input.split(&quot; &quot;))
    .anyMatch(availableGenres::contains);

It is worth noting that you could also use a Set of String instead of a List if the values are unique (include case-sensitive).

答案2

得分: 0

如果您想明确检查用户提供的字符串中哪个单词匹配的话:

str = "Puzzle Arcade";
String[] tokens = str.split("\\s+");

for each(String word : tokens){
  if (availableGenres.contains(word)){
    // 如果您想要的话,标记出现的单词
    // TRUE;
  }
}
英文:

If you want to explicitly check which word matches in the user-given string

str = &quot;Puzzle Arcade&quot;;
String[] tokens = str.split(&quot;\\s+&quot;);

for each(String word : tokens){
  if (availableGenres.contains(word)){
    //mark which word was present if you want to
    //TRUE;
    }
}

huangapple
  • 本文由 发表于 2020年5月19日 20:14:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/61890805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定