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;
}
Something like this with findFirst
and orElse
as :
return Arrays.stream(values())
.filter(carType -> carType.name().equals(name))
.findFirst().orElse(CarType.UNKNOWN);
You can use a stream this way:
public static CarType getByName(String name) {
return Arrays.stream(values())
.filter(carType -> carType.name().equals(name))
.findFirst()
.orElse(UNKNOWN);
}
BTW, when using IntellliJ (I am not affiliated to them ;)), it offers you an option to do this conversion automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With