Create enum using its string value | Java

You can create an enum using its name and you can get the string value easily but you cannot create the enum using its string value. Here's an example enum:

public enum Env {

    private final String url;

    Env(String url) {
    	this.url = url;

    public String getUrl() {
    	return this.url;

Create enum using its name: Env.valueOf("PROD")
Get the string value easily: Env.PROD.getUrl()

To create an enum using a string variable we need to create this over-complicated function:

public static Env fromValue(String url) {
    return Arrays.stream(values()).filter(x -> x.type.equals(url)).findFirst()
    	orElseThrow(() -> new IllegalArgumentException("Can't create Env from url " + url));

Now it's easy, just call Env.fromValue("https://hanki.dev")


- 0 toasts