Java getting the Enum name given the Enum Value

前端 未结 5 583
轻奢々
轻奢々 2020-12-15 14:55

How can I get the name of a Java Enum type given its value?

I have the following code which works for a particular Enum type, can I make it more

5条回答
  •  萌比男神i
    2020-12-15 15:34

    In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

    Using ForEach:

    List category = Arrays.asList(Category.values());
    category.stream().forEach(eachCategory -> {
                if(eachCategory.toString().equals("3")){
                    String name = eachCategory.name();
                }
            });
    

    Or, using Filter:

    When you want to find with code:

    List categoryList = Arrays.asList(Category.values());
    Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);
    
    System.out.println(category.toString() + " " + category.name());
    

    When you want to find with name:

    List categoryList = Arrays.asList(Category.values());
    Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);
    
    System.out.println(category.toString() + " " + category.name());
    

    Hope it helps! I know this is a very old post, but someone can get help.

提交回复
热议问题