According to previous answers, in particular from @Alexis I wrote some code to check booth approach (from Java 7 and Java 8). Maybe this can be useful for new users on Java 8.
So, I've made some changes in original answer. First of all, I put some unit test and I added two wrapping methods verifyNames() and contains(). Second, we can use a default behavior when unexpected action occurs, in this case, when the appleApproachTwo.fromValueJava8() was called with null or an not existing enum value.
Finally, the last change uses the potential uses for java.util.Optional objects. In this case, we can protect the environment to crash due to inconsistency to null objects. There are more discussion about Default Values, Optional and orElse() method at Default Values and Actions
public enum Food {
APPLE, APPLE2, APPLE3, BANANA, PINEAPPLE, CUCUMBER, NONE;
private static final Food[] APPLES = new Food[] {APPLE, APPLE2, APPLE3};
// approach one
// java7: conventional use
public Food fromValueJava7(String value) {
for (Food type : Food.values()) {
if (verifyNames(type, value)) {
return contains(Food.APPLES, type) ? Food.APPLE : type;
}
}
return null;
}
// approach two
// java8: how to include the array check for APPLES?
public Food fromValueJava8(String value) {
return Arrays.stream(Food.values())
.filter(type-> verifyNames(type, value))
.map(type -> contains(Food.APPLES, type) ? Food.APPLE : type)
.findFirst()
.orElse(Food.NONE);
}
private boolean contains(Food[] apples, Food type) {
return ArrayUtils.contains(apples, type);
}
private boolean verifyNames(Food type,String other) {
return type.name().equalsIgnoreCase(other);
}
}
// FoodTest
//
public class FoodTest {
@Test
public void foodTest(){
Food appleApproachOne = Food.APPLE;
// from approach one
assertEquals( appleApproachOne.fromValueJava7("APPLE"), Food.APPLE);
assertEquals( appleApproachOne.fromValueJava7("APPLE2"), Food.APPLE);
assertEquals( appleApproachOne.fromValueJava7("APPLE3"), Food.APPLE);
assertEquals( appleApproachOne.fromValueJava7("apple3"), Food.APPLE);
assertNull ( appleApproachOne.fromValueJava7("apple4") );
assertNull ( appleApproachOne.fromValueJava7(null) );
Food appleApproachTwo = Food.APPLE;
//from approach two
assertEquals( appleApproachTwo.fromValueJava8("APPLE"), Food.APPLE);
assertEquals( appleApproachTwo.fromValueJava8("APPLE2"), Food.APPLE);
assertEquals( appleApproachTwo.fromValueJava8("APPLE3"), Food.APPLE);
assertEquals( appleApproachTwo.fromValueJava8("apple3"), Food.APPLE);
assertEquals( appleApproachOne.fromValueJava8("apple4"), Food.NONE);
assertEquals( appleApproachTwo.fromValueJava8(null), Food.NONE);
}
}