Reputation: 331
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
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
Reputation: 56433
You can use the stream API:
String[] result =
Arrays.stream(s)
.filter(a -> a.startsWith("AB"))
.toArray(String[]::new);
Upvotes: 5
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