user12121548
user12121548

Reputation:

Check if string exists in ArrayList

I have an ArrayList with genres:

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

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?

Upvotes: 1

Views: 288

Answers (2)

Jason
Jason

Reputation: 5246

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 = "Puzzle Arcade";

boolean contains = Stream.of(input.split(" "))
    .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).

Upvotes: 2

Hashir
Hashir

Reputation: 400

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

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

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

Upvotes: 0

Related Questions