-1

I have an enum Foo

public enum Foo {

    A("first"),

    B("second"),

    private final String value;

    private Foo(String value) {
        this.value = value;
    }

    public String value() {
        return this.value;
    }

}

Below I am trying to check if a string is contained in my enum.

public boolean isValidFoo(String fooStr) {
return EnumSet.allOf(Foo.class)
                        .contains(Foo.valueOf(fooStr.toUpperCase()));
}

This works when I send A or B for fooStr. How to make it work when I send first or second for fooStr?

8
  • 6
    don't call valueOf(), call value(); that's the name of your method that returns the value. Better yet, rename it getValue(), it 'll make the distinction more clear Commented Sep 20, 2019 at 7:08
  • 2
    You can create a Set with Arrays.stream(Foo.values()).map(Foo::value).collect(toSet()), store this Set in a static field somewhere, and use theSet.contains(fooStr). Commented Sep 20, 2019 at 7:19
  • possibilities, depends on usage: use streams with map and filter to find enum; static HashMap created at start mapping values to enum; a static Set also created at start containing all values; or ... Commented Sep 20, 2019 at 7:22
  • @Stultuske I do not understand how calling value would help in that? (contains checks for an enum instance) Commented Sep 20, 2019 at 7:24
  • @CarlosHeuberger it's the name of his getter, that's how he gets the value. Commented Sep 20, 2019 at 7:26

2 Answers 2

0

You can try this..

public boolean isValidFoo(String fooStr) {
    return Arrays.stream(Foo.values())
            .anyMatch(e -> e.value.equals(fooStr));
}
Sign up to request clarification or add additional context in comments.

1 Comment

add map(Foo::value) instead of using e.value (when using functional, lets stay functional)
0

You can add a method

  public static Foo getEnum(String value) {
        for (Foo foo : Foo.values()) {
            if (foo.value.equals(value)) {
                return foo;
            }
        }
        return null;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.