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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With