Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent in java 8 from guava Enums.getIfPresent() that will return java.util.Optional?

I have the following code from an old group that is using guava Optional and Enums (getIfPresent).

// getNameAsString returns the string literal but I want to safely convert
// to an enum and return an java.util.Optional <MessageName>.
// MessageName is an enum
Optional<MessageName> msgName = Enums.getIfPresent(MessageName.class, obj.getMessage().getNameAsString());

How can I convert this to java 8? What is the equivalent of guava Enums.getIfPresent in java 8 that would return an java.util.Optional?

like image 375
genxgeek Avatar asked Mar 09 '15 00:03

genxgeek


1 Answers

A more Stream-idiomatic way with some generics sprinkled on the method signature:

public static <T extends Enum<T>> Optional<T> valueOf(Class<T> clazz, String name) {
    return EnumSet.allOf(clazz).stream().filter(v -> v.name().equals(name))
                    .findAny();
}

To test:

enum Test {
    A;
}

public static void main(String[] args) {
    Stream.of(null, "", "A", "Z").map(v -> valueOf(Test.class, v))
            .forEach(v -> System.out.println(v.isPresent()));
}

Expected output:

false
false
true
false
like image 95
h.j.k. Avatar answered Jan 01 '23 22:01

h.j.k.