Java Lambda | Find position first occurrence of an array of strings in a string

AsfK :

I want to build a method int getIndexOfFirstFound(String text, String[] words).

The method receive a text and array of words and should return the index of the first word found.

I know to do it with simple iteration, like this:

for (String word : words) {
    if (text.indexOf(word) != -1) return text.indexOf(word);
}
return -1;

but for my training I look how to do it with lambda, if it possible... I know I can check if the string contain a word from the array: Arrays.stream(words).parallel().anyMatch(text::contains) but I don't know how to return the index..

Will be glad to know how to find the first found word index with modern way, thanks!

P.S Example:

Text = "Hello I'm your text, how are you?" Words = ["your", "are"]

The result should be index of "your" (10)

ernest_k :

The simplest equivalent of your for loop is

int getIndexOfFirstFound(String text, String[] words) {
    return Arrays.stream(words)
            .mapToInt(text::indexOf)
            .filter(i -> i >= 0)
            .findFirst()
            .orElse(-1);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415510&siteId=1