Home > Mobile >  How to filter a list according to filter list except of item on another list?
How to filter a list according to filter list except of item on another list?

Time:10-03

I have some algorithmic challange:

Suppose I have the following list of strings:

{"South", "East", "West", "North"}

Now, I have a stream of items as an input.

For example:

{"South", "North korea", "East", "South carolina", "West", "North"}

As a general rule, I want to remove all the stream items which contains the items in the first list.

But there may be some exceptions. The exceptions might be set in another list. For example:

{"South korea", "North korea"} 

etc.

Notice, the exceptions list can include a large number of items, so I don't want to test each one of items implicitly.

On the other hand, I wouldn't like to have south carolina on the output list, but only the ones that in the excptions listm, and of course the ones that are not part of the first list.

So, the output of the above example should be:

{"North korea"}

I tried something like this (and some more variations) but obviously it isn't correct (Java):

    return
            Arrays.stream(illegalWordList).noneMatch(word::contains) &&
            Arrays.stream(excludedFromIllegalWordsList).noneMatch(word::contains);

Can you assist please?

Thank you!

CodePudding user response:

Not sure if I understood your question correctly, but to me it seems like you're close to a correct solution, just some flipped logic. Try

Arrays.stream(words).filter(word => {
    return Arrays.stream(illegalWordList).noneMatch(word::contains) 
        || Arrays.stream(excludedFromIllegalWordsList).anyMatch(word::contains)
    })

This essentially says "keep all items that don't contain anything blacklisted, or contain anything whitelisted"

  • Related