Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match an EXACT String in ArrayList<String>

I want to match an exact string in an ArrayList<String>.

Currently this code will execute if myArrayList.contains(wordImLookingFor).

if (myArrayList.contains(exactWordImLookingFor)) {
    Toast.makeText(getApplicationContext(), "Match", Toast.LENGTH_SHORT).show();
}

In summary, I'm looking for the code to execute when the entire String "dude" is entered, not just "d" or "du" or "dud".


2 Answers

If you want to see if a string is in the arraylist try this:

for (String s : myArrayList)
{
    if (s.equals(wordImLookingFor))
    {
        // Run your code here
    }
}

or

if (myArrayList.contains(wordImLookingFor))
{
    // Run your code here
}

If you want to see if a string entered is a substring of anything in the arraylist, try this:

for (String s : myArrayList)
{
    if (s.contains(wordImLookingFor))
    {
        // Run your code here
    }
}

This should work for your example of myArrayList containing "dude" and the user inputting "d".

like image 158
Akshay Avatar answered Sep 16 '25 00:09

Akshay


Java's ArrayList.contains() uses the equals() method, which matches only exactly

How does a ArrayList's contains() method evaluate objects?

like image 36
MikeB Avatar answered Sep 15 '25 22:09

MikeB