Home » Java » What is the difference between these two Enum(s) in Java-Exceptionshub

What is the difference between these two Enum(s) in Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


I have a String object: String theLanguage = "de";

I have these Two Enums:-

Enum 1:

public enum Lang

   private String lang;

   Lang(String lang) {
      this.lang = lang;

   public String lang() {
      return lang;

and Enum 2:

public enum Lang
   French(1, "fr"),
   German(2, "de"),
   English(3, "en"), 
   Italian(4, "it"),
   Spanish(5, "sp");

   final int languageID;

   private final String code;

   Lang( int languageID, String code)
      this.languageID = languageID;
      this.code= code;

———————— My Question —————————–

Q 1– What is the Difference between these two Enums ( Basically in 2nd Enum, why there are int values) ?

Q 2What I need to Do OR Add in 2nd Enum in Order to Search/Match the theLanguage object with Enum2. ?

How to&Answers:

1 – The second one can be searched for through both the string and int value (if for example you know the id of the language but not its code). Idk what “WhoisRIR” is doing in the place where your constructor should be.

2 – You need to add a getter for the code string and then foreach the enum until you find a element with code identical to theLanguage.


the 2nd just has an extra parameter, the languageID

Add this code to 2nd Enum in order to search by code (e.g “de”)

private static Map<String, Lang> reverseLookup = Arrays.stream(values())
             .collect(Collectors.toMap(Lang::getCode, Function.identity()));

public String getCode() {
    return code;

public static Lang fromCode(final String code) {
    return reverseLookup.get(code);