首页 > 解决方案 > Java8枚举避免多个if else

问题描述

在 java 8 中,是否有任何选项可以避免多个 if else 检查枚举值并执行特定操作。我不喜欢使用下面的例子吗?

if enum equals A 
 PRINT A
else if enum equals B
 PRINT B
else if enum equlas C
 PRINT C

标签: javaif-statementenumsjava-8

解决方案


您正在寻找的是switch陈述。不仅在 Java 8 中,您还可以enums在所有以前的 Java 版本中打开。考虑以下代码:

public class Dummy {


    enum MyENUM {
        A,
        B,
        C
    }


    public static void main(final String[] args) {
        MyENUM myENUM = MyENUM.A;
        switch (myENUM) {
            case A:
                System.out.println(MyENUM.A);
                break;
            case B:
                System.out.println(MyENUM.B);
                break;
            case C:
                System.out.println(MyENUM.C);
                break;
        }
    }
}

如果您不想使用switch语句,此页面提供了switch语句的各种替代方案。

替换的方法之一switch是创建地图。考虑下面的例子:

public static void main(final String[] args) {

    Map<MyENUM,Runnable> map = new HashMap<>();
    map.put(MyENUM.A,() -> System.out.println(MyENUM.A));
    map.put(MyENUM.B,() -> System.out.println(MyENUM.B));
    map.put(MyENUM.C,() -> System.out.println(MyENUM.C));

    MyENUM myENUM = MyENUM.A;
    map.get(myENUM).run();
}

产生以下结果:

A

推荐阅读