guava icon indicating copy to clipboard operation
guava copied to clipboard

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

Open dongritengfei opened this issue 9 years ago • 3 comments

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;
  }

dongritengfei avatar Sep 10 '17 20:09 dongritengfei

Can't you just do:

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

Stephan202 avatar Sep 10 '17 20:09 Stephan202

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

kluever avatar Sep 11 '17 04:09 kluever

@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

dongritengfei avatar Sep 12 '17 03:09 dongritengfei