Created
July 10, 2019 17:14
-
-
Save philwebb/c2c1f4eb43a514f21c1b67f2df982082 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.EnumSet; | |
import java.util.Objects; | |
import java.util.Optional; | |
import java.util.function.Function; | |
public class Enums { | |
public static <E extends Enum<E>, T> Optional<E> lookup(Class<E> elementType, Function<E, T> extractor, T value) { | |
return EnumSet.allOf(elementType).stream() | |
.filter(candidate -> Objects.equals(extractor.apply(candidate), value)).findFirst(); | |
} | |
} | |
enum MyEnum { | |
CONSTANT_NAME("constant name"); | |
private final String constantName; | |
MyEnum(String contantName) { | |
this.constantName = contantName; | |
} | |
public static Optional<MyEnum> byConstantName(String name) { | |
return Enums.lookup(MyEnum.class, f -> f.constantName, name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment