Creating a lookup method for an Enum
Without lambdas:
public enum Type {
INFO,
WARNING,
ERROR;
final static Map<String, Type> lookup = new HashMap<String, Type>();
static {
for(Type type : Type.values()) {
lookup.put(type.name().toLowerCase(), type);
}
}
public static Type of(String value){
Type val = lookup.get(value == null ? null : value.toLowerCase());
if(val == null){
val = ERROR;
}
return val;
}
}
With lambda:
public enum Type {
INFO,
WARNING,
ERROR;
final static Map<String, Type> lookup = Arrays.stream(Type.values())
.collect(Collectors.toMap(t -> t.name().toLowerCase(), Function.identity()));
public static Type of(String value){
Type val = lookup.get(value == null ? null : value.toLowerCase());
if(val == null){
val = ERROR;
}
return val;
}
}