CoralCode Web programming snippets

2Aug/130

Java – Convert string to enum

To convert a string to an enum value in Java you can simply use the valueOf method on your enum as the following example demonstrates:

public enum Fruit {
    APPLE, BANANA, ORANGE
}

Fruit myFriut = Fruit.valueOf("APPLE");

However this solution is case sensitive. To solve this problem we need to add an extra method to our enum that will returns with the correct value in a case insensitive way.

public enum Fruit {
	APPLE, BANANA, ORANGE;
	
	public static Fruit getValue(String str) {
		if (APPLE.name().equalsIgnoreCase(str)) {
			return APPLE;
		} else if (BANANA.name().equalsIgnoreCase(str)) {
			return BANANA;
		} else if (ORANGE.name().equalsIgnoreCase(str)){
			return ORANGE;
		}
		return null;
	}
}
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.