C
C
Clean Coder2020-09-15 23:12:48
Java
Clean Coder, 2020-09-15 23:12:48

How to check if a given element is in an enum?

Good afternoon! The question arose:
Is there some simple way to check whether an element belongs to an enumeration?
Or do you need to write a separate function in each enam for this?

For example:

import java.util.Scanner;

public class Main {
    enum TestEnum { 
        One(1), Two(3), Three(3);
        
        private int code;
        
        TestEnum(int code) {
            this.code = code;
        }
    }
    
  public static void main(String[] args) {
      int n = new Scanner(System.in).nextInt();
      System.out.println("n in TestEnum?");
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Roo, 2020-09-15
@HustleCoder

Java 8+

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    enum TestEnum {
        One(1), Two(2), Three(3);

        private int code;

        TestEnum(int code) {
            this.code = code;
        }
    }

    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        boolean isPresent = Arrays.stream(TestEnum.values()).anyMatch(element -> element.code == n);
        System.out.println("n in TestEnum? " + isPresent);
    }
}

S
sergey, 2020-09-16
kuzmin @sergueik

the class Enum
has a static method to find out

import java.lang.Enum;
import java.lang.IllegalArgumentException;

public class EvalEnum {
  enum MyEnum {
    One(1), Two(2), Three(3);

    private int code;

    MyEnum(int code) {
      this.code = code;
    }
  }

  public static void main(String[] args) {
    System.out.println(
        String.format("%s in MyEnum? %b", args[0], isPresent(args[0])));
  }

  private static boolean isPresent(String data) {

    try {
      Enum.valueOf(MyEnum.class, data);
      return true;
    } catch (IllegalArgumentException e) {
      return false;
    }
  }
}

java EvalEnum One
One in MyEnum? true

java EvalEnum Zero
Zero in MyEnum? false

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question