Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return object from list while looping java 8

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;
}
like image 696
Chamly Idunil Avatar asked Dec 13 '22 19:12

Chamly Idunil


2 Answers

Something like this with findFirst and orElse as :

return Arrays.stream(values())
               .filter(carType -> carType.name().equals(name))
               .findFirst().orElse(CarType.UNKNOWN);
like image 132
Naman Avatar answered Dec 16 '22 08:12

Naman


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.

like image 29
user140547 Avatar answered Dec 16 '22 09:12

user140547