-1

How can I check if there is a specific set of letters inside of a value that is inside of an ArrayList?

ArrayList<String> words = new ArrayList<String>();
        words.add("Wooden Axe");
        words.add("Stone Axe");
        
        if(words.contains("Axe")) {
            //something
        }

Like how can I check if the values contains the String "Axe"?

Hagelsnow
  • 1
  • 1
  • 1
    words doesn't contain "Axe", you'll need to check the values in words. The easiest way is to use a stream(), filter on the values that contain "Axe" – Stultuske Nov 19 '21 at 11:19
  • do you want to check if any of the words contains "Axe" an then do something if true, or do you want to do something with each of the matching words? – Bentaye Nov 19 '21 at 11:35

3 Answers3

2

If you wanna do a processing afterwards, you can do :

words.stream()
     .filter(word -> word.contains("Axe")) // you only keep words with "Axe"
     .forEach(word -> System.out.println(word)); // you process them the way you want
1

You can use the Stream method allMatch();

if(words.stream().allMatch(word -> word.contains("Axe"))) {
  //something
}
  • 3
    I guess that [`Stream.anyMatch()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/Stream.html#anyMatch(java.util.function.Predicate)) is closer to what the OP wants. – Hulk Nov 19 '21 at 11:26
  • 1
    I understood he wants to check in all Strings, but if he want to check if at least one word inside the array list has "Axe", anyMatch() will resolve it for sure. – Maurício Generoso Nov 19 '21 at 11:31
0

For a more involved answer, you'd want to go through every item within the array list itself like so:

public static boolean ArrayContainsWord(String match){
  for(String word : words){
   if(word.Contains(match)){
     return true;
   }
  }
  return false;
}

If you'd like to find the exact word that matches with the word you want then you can change the return type of the method "ArrayContainsWord" to return a String instead of a boolean and in the return true line, return the word and return null when you can't find any.

Dharman
  • 30,962
  • 25
  • 85
  • 135