Opposite of .contains (does not contain)

JavaContains

Java Problem Overview


I have an if statement:

if (inventory.contains("bread"))

But now I want to check

  • if inventory contains "bread"
  • but does not contain "water".

How can I do this?

Java Solutions


Solution 1 - Java

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

Solution 2 - Java

Maybe

if (inventory.contains("bread") && !inventory.contains("water"))

Or

if (inventory.contains("bread")) {
    if (!inventory.contains("water")) {
        // do something here
    } 
}

Solution 3 - Java

For your questions, use below

if(inventory.contains("bread") && !inventory.contains("water")) {

System.out.println("Bread is there and water not there");

}

else{

System.out.println("Both or any one condition not met");

}

Another example: Just use ! sign before contains function.

like if you want to perform some action, like if list does contains say stack then add stack.

   if (!list.contains("stack")) {
        list.add("stack");
    }`

or another method, if index of search string is -1,

 if(list.indexOf("stack")==-1){
    list.add("stack");

}

Solution 4 - Java

I know we can use the '!' to get the opposite value of the String.contains() function. If you do not want to use the '!' symbol, use the following code:

if(inventory.contains("bread"))
{
    if(inventory.contains("water"))
    {
        //do nothing
    }
    else
    {
        //do what you intend to do
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTizer1000View Question on Stackoverflow
Solution 1 - JavaItsan AliasView Answer on Stackoverflow
Solution 2 - Javajoey rohanView Answer on Stackoverflow
Solution 3 - JavaAshish GuptaView Answer on Stackoverflow
Solution 4 - JavaSardaar54View Answer on Stackoverflow