I'm just starting with Java.
I wonder if there's a way to add a method so that any String can call that method, similar to how we have now string1.equals(string2)
that you could use string1.equalsOr(string2, string3, string4, string5)
.
I know I can make my own static method, but wonder if I could make it available to any string.
string1.equalsOr(string2, string3, string4, string5)
can be easily written as (Java 9+)
Set.of(string2, string3, string4, string5).contains(string1)
or (Java 9+)
List.of(string2, string3, string4, string5).contains(string1)
or (Java 8+)
Stream.of(string2, string3, string4, string5).anyMatch(string1::equals)
or (any Java)
Arrays.asList(string2, string3, string4, string5).contains(string1)
If you want to check equality of your string1
to a set of strings string2, string3, string4, string5
. It's better to use any collection (i.e. Set
or List
). For example, if you use
Arrays.asList(string2, string3, string4, string5).contains(string1)
it will give you the espected result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With