Skip to content

Instantly share code, notes, and snippets.

@philwebb
Created July 10, 2019 17:14
Show Gist options
  • Save philwebb/c2c1f4eb43a514f21c1b67f2df982082 to your computer and use it in GitHub Desktop.
Save philwebb/c2c1f4eb43a514f21c1b67f2df982082 to your computer and use it in GitHub Desktop.
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