Check if a String starts with any of the given prefixes in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say the string is −

String str = "Malyalam";

Let’s say the prefixes are in an array −

String[] prefixArr = { "Ga", "Ma", "yalam" };

Now, to check whether the string starts with any of the abive prefix, use the startsWith() −

if (Stream.of(prefixArr)
   .anyMatch(str::startsWith))
   System.out.println("TRUE");
else
   System.out.println("FALSE");

Following is an example to check is a string starts with any of the given prefixes −

Example

import java.util.stream.Stream;
class Main {
   public static void main(String[] args) {
      String str = "Malyalam";
      String[] prefixArr = { "Ga", "Ma", "yalam" };
      if (Stream.of(prefixArr)
         .anyMatch(str::startsWith))
         System.out.println("TRUE");
      else
         System.out.println("FALSE");
   }
}

Output

TRUE
raja
Published on 20-Sep-2019 10:54:13
Advertisements