packagecom.miracle.luna.lambda;importjava.util.Arrays;/*** @Author Miracle Luna
* @Date 2019/6/9 23:40
* @Version 1.0*/
public enumAlarmGrade {
ATTENTION("attention", "提示"),
WARNING("warning","警告"),
SERIOUS("serious", "严重"),
FAULT("fault", "故障"),
UNKNOWN("unknown", "未知");privateString key;privateString name;/***@paramkey
*@paramname*/AlarmGrade(String key, String name) {this.key =key;this.name =name;
}/***@returnReturns the key.*/
publicString getKey() {returnkey;
}/***@returnReturns the name.*/
publicString getName() {returnname;
}/*** 根据Key得到枚举的Value
* 普通for循环遍历,比较判断
*
*@paramkey
*@return
*/
public staticAlarmGrade getEnumType(String key) {
AlarmGrade[] alarmGrades=AlarmGrade.values();for (int i = 0; i < alarmGrades.length; i++) {if(alarmGrades[i].getKey().equals(key)) {returnalarmGrades[i];
}
}returnAlarmGrade.UNKNOWN;
}/*** 根据Key得到枚举的Value
* 增强for循环遍历,比较判断
*
*@paramkey
*@return
*/
public staticAlarmGrade getEnumType1(String key) {
AlarmGrade[] alarmGrades=AlarmGrade.values();for(AlarmGrade alarmGrade : alarmGrades) {if(alarmGrade.getKey().equals(key)) {returnalarmGrade;
}
}returnAlarmGrade.UNKNOWN;
}/*** 根据Key得到枚举的Value
* Lambda表达式,比较判断(JDK 1.8)
*
*@paramkey
*@return
*/
public staticAlarmGrade getEnumType2(String key) {
AlarmGrade[] alarmGrades=AlarmGrade.values();
AlarmGrade result=Arrays.asList(alarmGrades).stream()
.filter(alarmGrade->alarmGrade.getKey().equals(key))
.findFirst().orElse(AlarmGrade.UNKNOWN);returnresult;
}/*** 根据Key得到枚举的Value
* Lambda表达式,比较判断(JDK 1.8)
*
*@paramkey
*@return
*/
public staticAlarmGrade getEnumType3(String key) {returnArrays.asList(AlarmGrade.values()).stream()
.filter(alarmGrade->alarmGrade.getKey().equals(key))
.findFirst().orElse(AlarmGrade.UNKNOWN);
}public static voidmain(String[] args) {
String grade= "attention";
System.out.println("第一种方式:普通for循环遍历,比较判断 \n" + grade + ": " +AlarmGrade.getEnumType(grade).getName());
System.out.println("\n第二种方式:增强for循环遍历,比较判断 \n" + grade + ": " +AlarmGrade.getEnumType1(grade).getName());
System.out.println("\n第三种方式:Lambda表达式,比较判断 \n" + grade + ": " +AlarmGrade.getEnumType2(grade).getName());
System.out.println("\n第四种方式:Lambda表达式,比较判断 \n" + grade + ": " +AlarmGrade.getEnumType3(grade).getName());
}
}