Java exists in enum

How to check if an enum contains String in Java

Enum was introduced in Java 1.5 as a new type whose fields consist of a fixed set of constants.

An enum type is a special data type that enables a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

Common examples include Days of Week (values of SUNDAY,MONDAY,TUESDAY) .

Table of Content :

When working with java programming, Many times we need to check if an Enum contains a given String value. There are multiple ways to validate this.

1). EnumUtils class of Apache Commons Lang3 library
2). Create custom method
3). Using Java 8’s streams API

We will see them one by one.

 enum Day < SUNDAY("Sunday"), MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"); private String dayOfWeek; Day(String dayOfWeek) < this.setDayOfWeek(dayOfWeek); >public String getDayOfWeek() < return dayOfWeek; >public void setDayOfWeek(String dayOfWeek) < this.dayOfWeek = dayOfWeek; >> 

1). EnumUtils class of Apache Commons Lang

The EnumUtils class has a method called isValidEnum whichChecks if the specified name is a valid enum for the class. It returns a boolean true if the String is contained in the Enum class, and a boolean false otherwise.

 EnumUtils.isValidEnum(Day.class, "MONDAY") 

This method differs from Enum.valueOf(java.lang.Class, java.lang.String) in that checks if the name is a valid enum without needing to catch the exception.

Читайте также:  Java cancel all timers

The following code example demonstrates the usage of EnumUtils.isValidEnum()

 package com.javacodestuffs.core.enums; import org.apache.commons.lang3.EnumUtils; public class FindInEnumUsingLang3 < public static void main(String[] args) < // Is SATURDAY("Saturday") a part of the enum? System.out.println("Day Enum contains SUNDAY : " + EnumUtils.isValidEnum(Day.class, "SATURDAY")); >> output: Day Enum contains SUNDAY : true 

2). Using Custom Method

Create custom method as given below then you call isInEnum(«THURSDAY», Day.class).

FindInEnumUsingCustomMethod.java

 package com.javacodestuffs.core.enums; public class FindInEnumUsingCustomMethod < public static void main(String[] args) < // Is SATURDAY("THURSDAY") a part of the enum? System.out.println("Day Enum contains THURSDAY : " + isInEnum("THURSDAY", Day.class)); >public static <E extends Enum <E>> boolean isInEnum(String value, Class <E> enumClass) < for (E e: enumClass.getEnumConstants()) < if (e.name().equals(value)) < return true; >> return false; > > output: Day Enum contains THURSDAY : true 

3). Using Java 8’s streams API

In this case enumns are converted to array, anyMatch and equals method’s are used.You can also put this method directly into the Enum class, and remove one of the parameters.

 public boolean isInEnum(String value, Class<E> enumClass) < return Arrays.stream(enumClass.getEnumConstants()).anyMatch(e ->e.name().equals(value)); > 

FindInEnumUsingStream.java

 import java.util.Arrays; public class FindInEnumUsingStream < public static void main(String[] args) < System.out.println("Day Enum contains SUNDAY : "+isInEnum("SUNDAY", Day.class)); >public static boolean isInEnum(String dayOfWeek, Class <Day> enumClass) < return Arrays.stream(enumClass.getEnumConstants()).anyMatch(e - >e.name().equals(dayOfWeek)); > > output: Day Enum contains SUNDAY : true 

Post/Questions related to How to check if an enum contains String

Enum in Java
How to check enum contains value in java?
How to get value from enum in java?
How to convert enum to list in java?
How to get enum key from value in java?
How to pass enum as parameter in java?
How to use enum constructor in java?
How to use enum in switch case java?
How to override valueof in enum java?
What is the difference between iterator and enumeration in java?
How to get all enum values in java?

In this article, we have seen the How to check if an enum contains String in Java with examples. All source code in the article can be found in the GitHub repository.

Источник

Как проверить, что данный элемент входит в enum?

Добрый день! Возник вопрос:
Есть ли какой-то простой способ проверки принадлежности элемента перечислению?
Или для этого в каждом енаме нужно писать отдельную функцию?

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?"); >>

Простой 1 комментарий

leahch

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); > >
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(); System.out.println("n in TestEnum? " + isPresent(n)); >private static boolean isPresent(int n) < for (TestEnum testEnum : TestEnum.values()) < if (testEnum.code==n) return true; >return false; > >

sergueik

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

Источник

How to check if an enum value exists in Java

There are multiple ways to check if an enum contains the given string value in Java. You can use the valueOf() to convert the string into an enum value in Java. If the string is a valid enum value, the valueOf() method returns an enum object. Otherwise, it throws an exception.

Let us say we have the following enum representing the days of the week:

public enum Weekday  MONDAY(1, "Monday"), TUESDAY(2, "Tuesday"), WEDNESDAY(3, "Wednesday"), THURSDAY(4, "Thursday"), FRIDAY(5, "Friday"), SATURDAY(6, "Saturday"), SUNDAY(7, "Sunday"); private final int number; private final String value; Weekday(int number, String value)  this.number = number; this.value = value; > public int getNumber()  return number; > public String getValue()  return value; > > 

Since the enum type is a special data type in Java, the name of each enum is constant. For example, the name of Weekday.FRIDAY is FRIDAY . To search the enum by its name, you can use the valueOf() method, as shown below:

String str = "FRIDAY"; Weekday day = Weekday.valueOf(str.toUpperCase()); System.out.println(day); // FRIDAY 

The valueOf() method works as long as you pass a string that matches an enum name. If the given string does not match an enum name, an IllegalArgumentException is thrown:

// Fail due to case mismatch Weekday monday = Weekday.valueOf("Monday"); // Fail due to invalid value Weekday invalidStr = Weekday.valueOf("Weekend"); 

To handle exceptions gracefully, let us add a static function called findByName() to Weekday that searches the enum by name and returns null if not found:

public enum Weekday  // . public static Weekday findByName(String name)  for (Weekday day : values())  if (day.name().equalsIgnoreCase(name))  return day; > > return null; > > 

The findByName() method uses the values() method to iterate over all enum values and returns an enum object if the given string matches an enum name. Otherwise, it returns null as shown below:

System.out.println(Weekday.findByName("Monday")); // MONDAY System.out.println(Weekday.findByName("friday")); // FRIDAY System.out.println(Weekday.findByName("Weekday")); // null 

To search an enum by value, you can use the same valueOf() method you used above. This time, instead of using the name() method, use the getValue() method, as shown below:

public enum Weekday  // . public static Weekday findByValue(String value)  for (Weekday day : values())  if (day.getValue().equalsIgnoreCase(value))  return day; > > return null; > > 

The findByValue() method works to findByName() and returns an enum object that matches the enum value. So for Tuesday , you will get Weekday.TUESDAY . If the given value is invalid, the findByValue() method returns null as shown below:

System.out.println(Weekday.findByValue("Tuesday")); // TUESDAY System.out.println(Weekday.findByValue("friday")); // FRIDAY System.out.println(Weekday.findByValue("Fri")); // null 

You can also write a function to search an enum by an integer value. For example, to search a Weekday by the number field, you can use the following code:

public enum Weekday  // . public static Weekday findByNumber(int number)  for (Weekday day : values())  if (day.getNumber() == number)  return day; > > return null; > > 

The findByNumber() method compares the given number with the day’s number. If the number matches, it returns the matched object. Otherwise, it returns null as shown below:

System.out.println(Weekday.findByNumber(3)); // WEDNESDAY System.out.println(Weekday.findByNumber(5)); // FRIDAY System.out.println(Weekday.findByNumber(9)); // null 

You can also use Java 8 Streams to simplify the enum search. Let us rewrite the above findByNumber() method using streams:

public static OptionalWeekday> findByNumber(int number)  return Arrays.stream(values()).filter(weekday -> weekday.getNumber() == number) .findFirst(); > 

The above example code looks different from the previous codes because we have used Java 8 streams to implement the search. Also, instead of returning the enum itself, an Optional value of the Weekday is returned. For the null value, the findByNumber() method returns an empty Optional . Here is an example that uses the above method to check if the enum exists:

OptionalWeekday> weekday = Weekday.findByNumber(6); if (weekday.isPresent())  System.out.println("The number matches " + weekday.get().name()); > else  System.out.println("Number does not match."); > // The number matches SATURDAY 

You can also throw an exception instead of returning null or empty Optional . Let us again rewrite the findByNumber() to throw an IllegalArgumentException if the enum is not found:

public static Weekday findByNumber(int number)  return Arrays.stream(values()).filter(weekday -> weekday.getNumber() == number) .findFirst().orElseThrow(IllegalArgumentException::new); > 
System.out.println(Weekday.findByNumber(5)); // FRIDAY System.out.println(Weekday.findByNumber(8)); // Exception in thread "main" java.lang.IllegalArgumentException 

You might also like.

Источник

How to check if an enum contains String in Java

Enum was introduced in Java 1.5 as a new type whose fields consist of a fixed set of constants.

An enum type is a special data type that enables a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

Common examples include Days of Week (values of SUNDAY,MONDAY,TUESDAY) .

Table of Content :

When working with java programming, Many times we need to check if an Enum contains a given String value. There are multiple ways to validate this.

1). EnumUtils class of Apache Commons Lang3 library
2). Create custom method
3). Using Java 8’s streams API

We will see them one by one.

 enum Day < SUNDAY("Sunday"), MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"); private String dayOfWeek; Day(String dayOfWeek) < this.setDayOfWeek(dayOfWeek); >public String getDayOfWeek() < return dayOfWeek; >public void setDayOfWeek(String dayOfWeek) < this.dayOfWeek = dayOfWeek; >> 

1). EnumUtils class of Apache Commons Lang

The EnumUtils class has a method called isValidEnum whichChecks if the specified name is a valid enum for the class. It returns a boolean true if the String is contained in the Enum class, and a boolean false otherwise.

 EnumUtils.isValidEnum(Day.class, "MONDAY") 

This method differs from Enum.valueOf(java.lang.Class, java.lang.String) in that checks if the name is a valid enum without needing to catch the exception.

The following code example demonstrates the usage of EnumUtils.isValidEnum()

 package com.javacodestuffs.core.enums; import org.apache.commons.lang3.EnumUtils; public class FindInEnumUsingLang3 < public static void main(String[] args) < // Is SATURDAY("Saturday") a part of the enum? System.out.println("Day Enum contains SUNDAY : " + EnumUtils.isValidEnum(Day.class, "SATURDAY")); >> output: Day Enum contains SUNDAY : true 

2). Using Custom Method

Create custom method as given below then you call isInEnum(«THURSDAY», Day.class).

FindInEnumUsingCustomMethod.java

 package com.javacodestuffs.core.enums; public class FindInEnumUsingCustomMethod < public static void main(String[] args) < // Is SATURDAY("THURSDAY") a part of the enum? System.out.println("Day Enum contains THURSDAY : " + isInEnum("THURSDAY", Day.class)); >public static <E extends Enum <E>> boolean isInEnum(String value, Class <E> enumClass) < for (E e: enumClass.getEnumConstants()) < if (e.name().equals(value)) < return true; >> return false; > > output: Day Enum contains THURSDAY : true 

3). Using Java 8’s streams API

In this case enumns are converted to array, anyMatch and equals method’s are used.You can also put this method directly into the Enum class, and remove one of the parameters.

 public boolean isInEnum(String value, Class<E> enumClass) < return Arrays.stream(enumClass.getEnumConstants()).anyMatch(e ->e.name().equals(value)); > 

FindInEnumUsingStream.java

 import java.util.Arrays; public class FindInEnumUsingStream < public static void main(String[] args) < System.out.println("Day Enum contains SUNDAY : "+isInEnum("SUNDAY", Day.class)); >public static boolean isInEnum(String dayOfWeek, Class <Day> enumClass) < return Arrays.stream(enumClass.getEnumConstants()).anyMatch(e - >e.name().equals(dayOfWeek)); > > output: Day Enum contains SUNDAY : true 

Post/Questions related to How to check if an enum contains String

Enum in Java
How to check enum contains value in java?
How to get value from enum in java?
How to convert enum to list in java?
How to get enum key from value in java?
How to pass enum as parameter in java?
How to use enum constructor in java?
How to use enum in switch case java?
How to override valueof in enum java?
What is the difference between iterator and enumeration in java?
How to get all enum values in java?

In this article, we have seen the How to check if an enum contains String in Java with examples. All source code in the article can be found in the GitHub repository.

Источник

Оцените статью