publicenumColor{
RED, GREEN, BLUE;
@Overridepublic String toString(){
// No upper cases in my life!return name().toLowerCase();
}
publicstatic Color valueOfIgnoreCase(String name){
// Go uppercase or go home!return Color.valueOf(name.toUpperCase());
}
}
OverridetoString() to control the display format of an enum. Create a valueOfIgnoreCase method for case-insensitive matching, because valueOf() is final and immovable like a stubborn mule.
Customize enum strings with spaces
publicenumPaintingStyle{
IMPRESSIONISM("Impressionism"), // Monet, is that you? CUBISM("Cubism"), // Picasso, you square! SURREALISM("Surrealism"); // Dali, stop watching the clock!privatefinal String styleName;
PaintingStyle(String styleName) {
this.styleName = styleName;
}
@Overridepublic String toString(){
// No more screaming art movement names!return styleName;
}
publicstatic PaintingStyle fromStringWithSpaces(String str){
// Loop through like you're in an art gallery.for (PaintingStyle style : values()) {
if (style.styleName.equalsIgnoreCase(str.trim())) {
return style;
}
}
// Sorry, no abstract art today.thrownew IllegalArgumentException("No constant with text " + str + " found");
}
}
Handle spaces and custom values like a pro by mapping strings to enum values with fancy loop de loop. Guard your masterpiece from unforeseen exceptions when there is mismatch. Because art is subjective, but your code is not!
Improve lookup performance by mapping strings to enum
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
publicenumFlavor{
VANILLA("Vanilla"), // Standard as a kitchen backsplash. CHOCOLATE("Chocolate"), // Oh, the sweet smell of optimization. STRAWBERRY("Strawberry"); // Did someone say anchors in smoothie?privatestaticfinal Map<String, Flavor> FLAVOR_MAP =
Stream.of(Flavor.values())
.collect(Collectors.toMap(Object::toString, e -> e));
privatefinal String flavorName;
Flavor(String flavorName) {
this.flavorName = flavorName;
}
@Overridepublic String toString(){
return flavorName;
}
publicstatic Flavor fromString(String flavorName){
// It's like flavor Google search.return FLAVOR_MAP.getOrDefault(flavorName, null);
}
}
Leave slow and clunky iterations behind. Map your enum values to strings in record time, just like going from zero to hundred in flavor town.
Retrieve custom value, use error handling, and rock the interface
publicstatic <E extends Enum<E> & CustomValueEnum> E fromCustomValue(String customValue, Class<E> enumClass){
// Like finding a needle in a haystack, but EASY.return Arrays.stream(enumClass.getEnumConstants())
.filter(e -> e.getCustomValue().equals(customValue))
.findAny()
.orElseThrow(() -> new IllegalArgumentException("That's a no-no: " + customValue));
}
publicinterfaceCustomValueEnum{
// Every enum has a dream... to be a custom value!String getCustomValue();
}
Interfaces and Enums: a match made in heaven. Custom values at your fingertips, with specialised error handling is the cherry on top!
Play safe, avoid reflection risks
Reflective code is like a shiny new toy, but beware, it can lead to security risks and end up as an alien in your codebase if not handled correctly! Always remember, safe code is happy code!
Tweak your enum with advanced utilities
Customize your enum to your heart's content:
Filters: To strip away anything unnecessary.
Maps: To make sure you always find what you’re looking for.
Collectors: To compile everything you need in one place.
Feeling overwhelmed? Fear not, Google’s Guava library is here to your rescue!