Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add method .equalsOr() to String class

Tags:

java

string

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.

like image 425
Manuel Avatar asked Dec 08 '22 13:12

Manuel


2 Answers

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)
like image 121
Andreas Avatar answered Dec 31 '22 10:12

Andreas


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.

like image 29
dehasi Avatar answered Dec 31 '22 08:12

dehasi