1

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?

1
  • 3
    You have to split the incoming String, split and for each part check its presence in the list. Commented May 19, 2020 at 12:15

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Or anyMatch(availableGenres::contains).
Yeah, very well said, i'll change that.
0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.