Sam Crowley Sam Crowley - 7 months ago 8
Java Question

Find String in ArrayList Containing Phrase

I have an ArrayList of Strings and I want to find a String in that list containing another String.

Say if my list is:

{
apple fruit
carrot vegetable
cake dessert
}


I want to search this list for the phrase
apple
and get its index -- this would give me the index 0, in this case.

Is this possible?

EDIT: This is what I've tried, but not sure what to put in the if statement:

String msg = queue.get(0).getTitle();
for(int i = 0; i < messages.size(); i++) {
if(messages.get(i)...) {
messages.remove(i);
}
}

Answer
public static void main(String[] args) {
    List<String> data = new ArrayList<String>();
    String yourRequiredString = "dessert";
    data.add("apple fruit");
    data.add("carrot vegetable");
    data.add("cake dessert");
    for (int i = 0; i < data.size(); i++) {
        if (data.get(i).contains(yourRequiredString)) {
            System.out.println(i);
        }
    }
}

Hope this helps...