Guava: Feature Request: equal any objects for com.google.common.base.Objects

Created on 10 Sep 2017  路  3Comments  路  Source: google/guava

Example:

if (Objects.equal(status, "STOPPED") || Object.equal(status, "RELEASED") || Object.equal(status, "DELETED")) {
    // do something
}

Could we add a method Objects.equalAny(Object, Object...), then example will be:

if (Objects.equalAny(status, "STOPPED", "RELEASED","DELETED")) {
    // do something
}

It's simple, right?

Here is my implementation:

  public static boolean equalAny(@Nullable Object a, @Nullable Object... any) {
    if (any == null && a == null) {
      return true;
    } else if (any != null) {
      for (Object obj : any) {
        if (equal(a, obj)) {
          return true;
        }
      }
    }
    return false;
  }
package=base type=addition

Most helpful comment

+1 to @Stephan202 's suggestion (although I'd probably go a step further and extract a static constant ImmutableSet<String>).

All 3 comments

Can't you just do:

if (Arrays.asList("STOPPED", "RELEASED", "DELETED").contains(status)) {
    // do something
}

+1 to @Stephan202 's suggestion (although I'd probably go a step further and extract a static constant ImmutableSet<String>).

@Stephan202 Arrays.asList() no dependency and maybe more faster for several elements;
@kluever ImmutableSet.of() elegant and fast for much more elements;
Both ok, thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thecoop picture thecoop  路  4Comments

ernestp picture ernestp  路  3Comments

epkugelmass picture epkugelmass  路  4Comments

Lysergid picture Lysergid  路  4Comments

philgebhardt picture philgebhardt  路  3Comments