javajava-stream

How can I fetch enum value from a string?


I have enum class like this:

public enum Severity {

    HIGH("High level it is ", RED, DARK_RED),
    MEDIUM("Medium level it is ", AMBER, LIGHT_YELLOW),
    LOW("Low level it is ", GREEN, DARK_GREEN);
    private String value;

    private List<Colors> color;

    Severity(String value, Color... colors) {
        this.value = value;
        this.color = Arrays.asList(colors);
    }

    public static List<String> getSeverityKeys() {
        return EnumSet.allOf(Severity.class).stream()
            .map(Severity::name)
            .collect(Collectors.toList());
    }

    public static List<String> getSeverityValues() {
        return EnumSet.allOf(Severity.class).stream()
            .map(Severity::getValue)
            .collect(Collectors.toList());
    }

    public static Severity getDescriptionByColor(String color) {

        return EnumSet.allOf(Severity.class).stream()
            .filter(severity -> Severity.getToolDomainValues().equals(color))
            .findFirst()
            .orElse(null);
    }

    public String getValue() {
        return value;
    }

    public List<Color> getColor() {
        return color;
    }
}

Input : DARK_RED

output : High level it is

or

Input : DARK_GREEN

output : Low level it is

How can I achieve this using Java Stream functionality

I am trying to fix method getDescriptionByColor(String color)


Solution

  • I've made the suggestion that the colors comes from an enum Color, you may adapt


    You need to iterate over Severity.values() and find the ones that have the value you're looking for, then get the string (first parameter) of the find ones :

    static String getString(Color value) {
        return Arrays.stream(Severity.values())
                .filter(severity -> severity.getColorB().equals(value))
                .map(Severity::getString)
                .findFirst().orElse(null);
    }
    

    Use

    System.out.println(Severity.getString(Color.DARK_RED)); //High level it is
    System.out.println(Severity.getString(Color.DARK_GREEN)); // Low level it is