Is there some straight forward way to return object from list which map to condition we passed.
Ex :
public enum CarType {
TOYOTA,
NISSAN,
UNKNOWN;
public static CarType getByName(String name) {
for (CarType carType : values()) {
if (carType.name().equals(name)) {
return carType;
}
}
return UNKNOWN;
}
}
Is there some another way support by java 8 below method and for loop I have used.
public static CarType getByName(String name) {
for (CarType carType : values()) {
if (carType.name().equals(name)) {
return carType;
}
}
return UNKNOWN;
}
getByName(String)twice ? I find it confusing.valueOfmethod that everyEnumhas? It's not Java 8.equalsandequalsIgnoreCaseare.try { return valueOf(name); } catch(IllegalArgumentException ex) { return UNKNOWN; }