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


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

Updated on: 20-Sep-2019

325 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements