英文:
Is there a one-line way to write this same code but using some type of mutable map in Java 8?
问题
private Map<String, Object> contactQuestion = ImmutableMap.of("pageForm", "contactInfo", "questionList", Arrays.asList(ImmutableMap.of("active", false)));
我在一个JUnit测试的类级别定义了这个变量,但我意识到我需要让这些映射可变。我最初使用ImmutableMap类编写了这段代码,因为它提供了一种便捷的方式来内联构建映射。我发现在我的测试中,实际上需要改变这些映射。我尝试使用HashMap,但HashMap似乎没有类似于ImmutableMap的of()
的函数。这里是否有一些巧妙的替代方法?
感谢任何建议。
英文:
private Map<String,Object> contactQuestion = ImmutableMap.of("pageForm","contactInfo", "questionList",Arrays.asList(ImmutableMap.of("active",false)));
I'm defining this variable at the class level in a JUnit test, but I've realized I need the maps to be mutable. I wrote the code initially using the ImmutableMap class because it offered this convenient way of building the map in-line. I've found that in my tests I actually need to mutate these maps. I tried to use a HashMap but HashMap doesn't seem to have any function similar to ImmutableMap's of()
. Is there some clever alternative here?
Thanks for any advice
答案1
得分: 2
关于ImmutableMap.of
我不太确定,但自JDK 9以来,对于每个Map.of
,如果你想要它们都是可变的,你需要将它们传递给一个Map
实现。
英文:
Not certain about ImmutableMap.of
but since JDK 9
private Map<String,Object> contactQuestion = new HashMap<>
(Map.of("pageForm","contactInfo",
"questionList",Arrays.asList(Map.of("active",false))));
For each Map.of
you would need to pass that to a Map
implementation if you want them all to be mutable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论