user4213837
user4213837

Reputation: 215

Contains method not working properly in Java

I would like to check if a string contains a specified word. If the string contains that specified word i don't want to print that. Now there may be redundant words but i will only print unique words excluding my pre-defined word list for example, "traffic", "collapse". For that I am using Set to store the unique strings and checking that using if-statement and contains. But it is not working properly. Although my pre-defined restrictive word is "traffic" but still my program prints traffic along with all the words. It seems the filter/contains method is not working properly. P.S: I converted all the words in lowercase to avoid case sensitivity. Below is my code. Pls help me to understand what is wrong? I am using Java code.

import java.util.HashSet;
import java.util.Set;


public class SetTest {

    public static void main(String[] args) {
        Set<String> placeSet=new HashSet<String> ();

        String s1="traffic";
        String s2="mumbai";
        String s3="Mumbai";
        String s4="roadcollapse";

        placeSet.add(s1.toLowerCase());
        placeSet.add(s2.toLowerCase());
        placeSet.add(s3.toLowerCase());
        placeSet.add(s4.toLowerCase());

        for (String place:placeSet)
        {
            if (!place.contains("traffic") || !place.contains("collapse"))
            {
                System.out.println (place);
            }
        }

    }

}

Upvotes: 0

Views: 654

Answers (3)

hhrzc
hhrzc

Reputation: 2050

Convenient way for me - stream API

    placeSet.stream()
            .filter(p -> !p.contains("traffic"))
            .filter(p -> !p.contains("collapse"))
            .forEach(System.out::println);

Upvotes: 0

suvojit_007
suvojit_007

Reputation: 1728

If the string contains that specified word i don't want to print that.

Use && instead of ||

 for (String place:placeSet)
        {
            if (!place.contains("traffic") && !place.contains("collapse"))
            {
                System.out.println (place);
            }
        }

Upvotes: 1

Beri
Beri

Reputation: 11620

If you want to print a word only if it doesn't contain any of blacklisted words, then the condition should look like this:

 for (String place:placeSet)
    {
        if (!(place.contains("traffic") || place.contains("collapse"))) {
            System.out.println (place);
        }
    }

Because you want to print if word does not contain word_1 or word_1, so it should be NOT (condition1 OR condition2)

In case of multiple blacklisted words, you can work with a Set also:

public static void main(String[] args) {
    Set<String> blacklist = Stream.of("traffic","collapse").collect(Collectors.toSet());
    ...
    for (String place:placeSet) {
        if (blacklist.stream().noneMatch(place::contains)) {
            System.out.println (place);
        }
    }
}

Upvotes: 1

Related Questions