Arun Kumar V
Arun Kumar V

Reputation: 331

Check starts-with for each element in array

Is there any utility function in java which does String.startsWith for each element in string array?

For eg:

String[] s = {"ABC", "BBV", "ABCD", "NBHH"};

Is there any way to do :

array.startsWith("AB");

Returns ABC and ABCD

Upvotes: 2

Views: 2729

Answers (3)

Sudheesh Singanamalla
Sudheesh Singanamalla

Reputation: 2297

You could use Stream if you're using Java 8. In case you aren't then you'd probably want to use the solution below:

String s[]={"ABC","BBV","ABCD","NBHH"};

for (String i : s) {
    if (i.startsWith("AB")) { // startsWith() returns boolean
        System.out.println(i);
    }
}

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56433

You can use the stream API:

String[] result = 
      Arrays.stream(s)
            .filter(a -> a.startsWith("AB"))
            .toArray(String[]::new);

Upvotes: 5

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

If you are using Java 8, you can use filter like this :

String[] result = Stream.of(s).filter(a -> a.startsWith("AB")).toArray(String[]::new);

If you want to return a List you can use :

List<String> rst = Stream.of(s).filter(a->a.startsWith("AB")).collect(Collectors.toList());

Upvotes: 3

Related Questions