Test if a string contains any of the strings from an array
To check if a string contains any substring from an array, Java's Stream
and anyMatch
come to the rescue:
We use Arrays.stream
to cast a spell and turn our array into a stream. Then, anyMatch
— our secret keyword detective, does an efficient sweep through the input string, calling off the search as soon as any match is found.
Deep Dive: Multiple approaches and performance notes
Advantages of using Lists over arrays
Although arrays are one of Java's classic data structures, converting them to List
provides a whole horizon of flexibility:
Now you can add or remove elements from triggers
, no arrays were harmed during this process.
Case sensitivity handling
We're not all shouty on the internet, so case can vary:
Here, we make case insensitive checks. Whether it's 'FOO' or 'foo' — the laugh is still valid!
Going RegEx for intricate patterns
For scenarios that are more than just a knock-knock joke, regular expressions come handy:
Our pattern using Pattern.compile
and our trusty Matcher
allows us to handle more complex patterns. Be it a one-liner or a punny story, we're finding them all!
Utilising StringUtils for compact checks
Need a quick laugh? Enter StringUtils
from Apache Commons:
StringUtils.indexOfAny
does a quick check. If it returns anything but -1
, it means there's a funny word in there. Nice and easy!
Even More Options: Improving readability and performance
Keeping it simple with streams
For a small number of words, a regular stream laughs all the way to the performance bank, because parallel processing can sometimes be a bit too much fun for its own good.
Aiding readability with static methods
Packaging our joke detector into a static utility method not only makes the code read more like English but also recyclable:
Laughing all the way with large datasets
For a long list of funny words, consider using Java's built-in parallelStream(). It's a longer laugh track:
This can significantly improve performance, especially if you're running this at a comedy festival.
Simplifying syntax with method references
Java 8 introduced method references, making your joke-detection code easier to read:
Was this article helpful?