-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?

sk17261205
  • 421
  • 1
  • 5
  • 12
  • 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 – Stultuske Sep 20 '19 at 07: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)`. – Andy Turner Sep 20 '19 at 07: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 ... – user85421 Sep 20 '19 at 07:22
  • @Stultuske I do not understand how calling `value` would help in that? (`contains` checks for an enum instance) – user85421 Sep 20 '19 at 07:24
  • @CarlosHeuberger it's the name of his getter, that's how he gets the value. – Stultuske Sep 20 '19 at 07:26
  • I know, but will not work like "don't call valueOf(), call value()" - and call `value()` of what? `contains` just search for an instance of the enum - is is not functional either (as I know) – user85421 Sep 20 '19 at 07:29
  • Possible duplicate of [How to compare string to enum type in Java?](https://stackoverflow.com/questions/12682553/how-to-compare-string-to-enum-type-in-java) – borchvm Sep 20 '19 at 07:31
  • not duplicate of previous (about finding enum by name); **related**, but has some ideas, need changes: [Finding enum value with Java 8 Stream API](https://stackoverflow.com/q/27807232/85421) – user85421 Sep 20 '19 at 07:53

2 Answers2

0

You can try this..

public boolean isValidFoo(String fooStr) {
    return Arrays.stream(Foo.values())
            .anyMatch(e -> e.value.equals(fooStr));
}
Rowi
  • 545
  • 3
  • 9
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;
  }
jack
  • 26
  • 3