如何用Java Stream修复枚举方法,根据颜色字符串获取描述值?
getDescriptionByColor Method with Java Streams Let's walk through fixing this method step by step. The original implementation has two main issues: it calls a non-existent getToolDomainValues() method, and it doesn't properly check if the input color belongs to any Severity instance's color list. Here's how to fix it using Java Streams to meet your exact requirement:
Step 1: Fix the Core Logic
First, we need to convert the input color string (like DARK_RED) to a Color enum instance (since your Severity stores Color objects, not raw strings). Then, we'll use a Stream to find the matching Severity and return its description.
Fixed Method Code
public static Severity getDescriptionByColor(String colorStr) { try { // Convert input string to Color enum, handle case sensitivity Color targetColor = Color.valueOf(colorStr.toUpperCase()); // Use Stream to find the Severity that includes the target color return EnumSet.allOf(Severity.class).stream() .filter(severity -> severity.getColor().contains(targetColor)) .findFirst() .orElse(null); } catch (IllegalArgumentException e) { // Return null if input isn't a valid Color enum value return null; } }
How to Get the Description String
To retrieve the actual description text (like "High level it is ") for a given color, call the method and chain the getValue() method:
// Returns "High level it is " String highSeverityDesc = Severity.getDescriptionByColor("DARK_RED").getValue(); // Returns "Low level it is " String lowSeverityDesc = Severity.getDescriptionByColor("DARK_GREEN").getValue();
Key Improvements Explained
- String-to-Enum Conversion: Using
Color.valueOf(colorStr.toUpperCase())ensures we safely convert the input string to a validColorenum, and handles case-insensitive inputs (e.g., "dark_red" will work too). - Stream Filtering: The
filteroperation checks eachSeverity's color list to see if it contains the target color, which aligns perfectly with your requirement. - Error Handling: The try-catch block gracefully handles invalid color strings by returning
null, matching the original method's intended behavior.
Optional: Directly Return the Description String
If you want the method to return the description text directly instead of the Severity enum, you can adjust it like this:
public static String getDescriptionStringByColor(String colorStr) { try { Color targetColor = Color.valueOf(colorStr.toUpperCase()); return EnumSet.allOf(Severity.class).stream() .filter(severity -> severity.getColor().contains(targetColor)) .map(Severity::getValue) .findFirst() .orElse(null); } catch (IllegalArgumentException e) { return null; } }
Now calling getDescriptionStringByColor("DARK_RED") will directly return "High level it is ".
内容的提问来源于stack exchange,提问作者sushma

