在枚举字典中打印值

时间:2019-03-25 02:59:54

标签: java

我要打印使用Map字典类型创建的值

首先,我有一个Enum类,然后定义另一个静态变量(我认为当对象初始化时,它将运行一次吗?),在该静态变量中,我将为每个枚举创建字典。

枚举类:

public enum myEnumValues{
    testingFile1,
    testingFile2;

// this part I thought it will automatically make the dictionary based on the put I have specified? Here I use 2 put with values "check1" and "check2"

public static final Map<myEnumValues, String> var;
static{
        Map<myEnumValues, String> putting = new EnumMap<>(myEnumValues.class);
        putting.put(myEnumValues.testingFile1, "check1");
        putting.put(myEnumValues.testingFile2, "check2");
        var = Collections.unmodifiable(putting);
      }
}

我的测试班:

//Is there a way to print the dictionary value for both keys "testingFile1" and "testingFile2"? I think I understand it very wrong with my method. I am still learning Java.
import folder.data.myEnumValues;
@Test public void CheckTestForMyEnumValues(){
    Map<myEnumValues, String> putting = new EnumMap<>(myEnumValues.class);
    System.out.println(putting.get(myEnumValues.testingFile1));
    System.out.println(putting.get(myEnumValues.testingFile2));
}

我的预期结果应该是:

check1
check2

我创建此枚举字典类的目标:

1)我将创建另一个具有变量a的类。然后它将进行比较

if (x == myEnumValues.testingFile1){
    var a == myEnumValues.get(); // store the a with value for key "testingFile1".
}else{
    var a == null;
}

我的测试类主要是为我获取键的值,然后我将添加更多代码,但是现在我什至无法创建带有枚举的字典,而且我什至不知道字典是否已制成并调用每个枚举的值。这就是为什么我提出这个问题。

2 个答案:

答案 0 :(得分:1)

使用您在static块中创建的映射来访问值。不要创建新地图,因为新地图不包含任何内容。

@Test public void CheckTestForMyEnumValues(){
    System.out.println(var.get(myEnumValues.testingFile1));
    System.out.println(var.get(myEnumValues.testingFile2));
}

答案 1 :(得分:0)

您可以使用以下单行(Java 8)打印地图中所有条目的键和值

putting.forEach((k, v) -> System.out.println(String.format("Key: %s, value: %s", k, v)));