Return object from list while looping java 8

Viewed 2922

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;
}
3 Answers

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.

another option

enum CarType {
    TOYOTA, NISSAN, UNKNOWN;

    public static CarType getByName(String name) {
        return Stream.of(CarType.values())
          .filter(x -> x.name().equals(name))
          .findFirst()
          .orElse(UNKNOWN);
    }
}
Related