Finding the indices of multiple words in a string In response to a recent SO question, I answered with the following code, and was wondering if anyone had any input on it. I'm always looking for an opprotunity to learn!

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class WordFinder {

    public static void main(String[] args) {
        String phrase = "0123hello9012hello8901hello7890";
        String[] words = { "hello", "90" };

        Map&lt;String, Stack&lt;Integer&gt;&gt; dest = findWordsInString(words, phrase);

        System.out.println(dest.toString());
    }

    public static Map&lt;String, Stack&lt;Integer&gt;&gt; findWordsInString(String[] words, String phrase) {
        Map&lt;String, Stack&lt;Integer&gt;&gt; dest = new HashMap&lt;&gt;();

        for (String word : words) {
            Stack&lt;Integer&gt; locations = new Stack&lt;&gt;();

            for (int loc = -1; (loc = phrase.indexOf(word, loc + 1)) != -1;) {
                locations.add(loc);
            }

            dest.put(word, locations);
        }

        return dest;
    }
}


Program Output:


{90=[9, 19, 29], hello=[4, 13, 22]}
Map&lt;String, Stack&lt;Integer&gt;&gt; dest = findWordsInString(words, phrase);

I don't see the need at all for a Stack here. And not a Map either.

Let's say that you would want to find the third occourance of the word, and then randomly the first, and the fifth, and the second... Then you would want to store the indices in a List, not a Stack.

And why deal with multiple words at the same time? The way that your method is written, it makes more sense to search for all occurances of one word at a time.

As for the very important for loop, while it is totally alright to write it like that, I would personally prefer a while loop with something like this: (there is a bunch of variations for how you could do this)

int loc = phrase.indexOf(word);
while (loc != -1) {
   locations.add(loc);
   loc = phrase.indexOf(word, loc + 1);
}


It makes it easier to read the code, in my opinion.