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: 2019-09-20T10:54:48+05:30

531 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements