Get element starting with letter from List

283 views Asked by At

I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working.

List<String> sp = Arrays.asList(splited);
int i2 = sp.indexOf("^w.*$"); 
2

There are 2 answers

0
Bubletan On BEST ANSWER

The indexOf method doesn't accept a regex pattern. Instead you could do a method like this:

public static int indexOfPattern(List<String> list, String regex) {
    Pattern pattern = Pattern.compile(regex);
    for (int i = 0; i < list.size(); i++) {
        String s = list.get(i);
        if (s != null && pattern.matcher(s).matches()) {
            return i;
        }
    }
    return -1;
}

And then you simply could write:

int i2 = indexOfPattern(sp, "^w.*$");
1
Maroun On

indexOf doesn't accept a regex, you should iterate on the list and use Matcher and Pattern to achieve that:

Pattern pattern = Pattern.compile("^w.*$");
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    System.out.print(matcher.start());
}

Maybe I misunderstood your question. If you want to find the index in the list of the first string that begins with "w", then my answer is irrelevant. You should iterate on the list, check if the string startsWith that string, and then return its index.