4

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;
}
4
  • 3
    Why did you post getByName(String) twice ? I find it confusing. Commented Nov 14, 2017 at 4:15
  • 1
    Are you looking for the valueOf method that every Enum has? It's not Java 8. Commented Nov 14, 2017 at 4:15
  • I would have thought that OP knew what equals and equalsIgnoreCase are. Commented Nov 14, 2017 at 5:22
  • try { return valueOf(name); } catch(IllegalArgumentException ex) { return UNKNOWN; } Commented Nov 15, 2017 at 11:09

3 Answers 3

5

Something like this with findFirst and orElse as :

return Arrays.stream(values())
               .filter(carType -> carType.name().equals(name))
               .findFirst().orElse(CarType.UNKNOWN);
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.