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

I have the following code from an old group that uses 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 will return java.util.Optional?

+6
source share
3 answers

You can fake it using Java 8 as follows

 import java.util.Optional; Optional<MessageName> msgName = getValueOf(MessageName.class,obj.getMessage().getNameAsString()); public static Optional<MessageName> getValueOf(Class<MessageName> enumType, String name){ MessageName enumValue = null; try{enumValue =Enum.valueOf(enumType, name); }catch(IllegalArgumentException ex ){ //log this here } return Optional.ofNullable(enumValue); } 

The static method getValueOf deals with IllegalArgumentException

+2
source

More Stream didiomatic path with some generics sprinkled with a 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 check:

 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 Result:

 false false true false 
+4
source

I wanted to make a slightly cleaner version of @iamiddy's answer, but unfortunately I cannot put it in a comment, and it may not be possible to edit this answer.

This example indicates that there is no benefit if there is a temporary value that can be zero.

 public static <T extends Enum<T>> Optional<T> getValueOf(Class<T> enumType, String name) { try { return Optional.of(Enum.valueOf(enumType, name)); } catch(IllegalArgumentException ex) { return Optional.empty(); } } 
+1
source

Source: https://habr.com/ru/post/983523/


All Articles