我有这样的枚举类:
public enum Severity {
HIGH("High level it is ", RED, DARK_RED),
MEDIUM("Medium level it is ", AMBER, LIGHT_YELLOW),
LOW("Low level it is ", GREEN, DARK_GREEN);
private String value;
private List<Colors> color;
Severity(String value, Color... colors) {
this.value = value;
this.color = Arrays.asList(colors);
}
public static List<String> getSeverityKeys() {
return EnumSet.allOf(Severity.class).stream()
.map(Severity::name)
.collect(Collectors.toList());
}
public static List<String> getSeverityValues() {
return EnumSet.allOf(Severity.class).stream()
.map(Severity::getValue)
.collect(Collectors.toList());
}
public static Severity getDescriptionByColor(String color) {
return EnumSet.allOf(Severity.class).stream()
.filter(severity -> Severity.getToolDomainValues().equals(color))
.findFirst()
.orElse(null);
}
public String getValue() {
return value;
}
public List<Color> getColor() {
return color;
}
}
输入:DARK_RED
输出:高水平
OR
输入:DARK_GREEN
输出:低电平
如何使用JAVA Stream功能实现这一目标
我正在尝试修复方法-getDescriptionByColor(字符串颜色)
答案 0 :(得分:2)
我建议颜色来自枚举Color
,您可以修改
您需要遍历Severity.values()
并找到具有您要查找的值的对象,然后获取所查找对象的字符串(第一个参数):
static String getString(Color value) {
return Arrays.stream(Severity.values())
.filter(severity -> severity.getColorB().equals(value))
.map(Severity::getString)
.findFirst().orElse(null);
}
使用
System.out.println(Severity.getString(Color.DARK_RED)); //High level it is
System.out.println(Severity.getString(Color.DARK_GREEN)); // Low level it is
答案 1 :(得分:0)
我们还可以使用 EnumSet 代替Arrays Stream
使用 EnumSet
class TestClass {
public static void main(String[] args) {
String value = "DARK_RED";
Optional<String> res = EnumSet.allOf(Severity.class)
.stream()
.filter(severity -> severity.s3.equals(value))
.map(Severity::getFirstString)
.findFirst();
if(res.isPresent()){
System.out.println(res.get().toString());
}
}
}
使用 Arrays Stream
class TestClass {
public static void main(String[] args) {
String value = "DARK_RED";
Optional<String> res = Arrays.stream(Severity.values())
.filter(severity -> severity.s3.equals(value))
.map(Severity::getFirstString)
.findFirst();
if(res.isPresent()){
System.out.println(res.get().toString());
}
}
}
enum Severity {
HIGH("High level it is ", "RED", "DARK_RED"),
MEDIUM("Medium level it is ", "AMBER", "LIGHT_YELLOW"),
LOW("Low level it is ", "GREEN", "DARK_GREEN");
String s1;
String s2;
String s3;
Severity(String s1, String s2, String s3){
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
}
public String getFirstString(){
return this.s1;
}
}