Is there a one-line way to write this same code but using some type of mutable map in Java 8?

huangapple go评论60阅读模式
英文:

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&lt;String,Object&gt; contactQuestion = ImmutableMap.of(&quot;pageForm&quot;,&quot;contactInfo&quot;, &quot;questionList&quot;,Arrays.asList(ImmutableMap.of(&quot;active&quot;,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&lt;String,Object&gt; contactQuestion = new HashMap&lt;&gt; 
     (Map.of(&quot;pageForm&quot;,&quot;contactInfo&quot;, 
          &quot;questionList&quot;,Arrays.asList(Map.of(&quot;active&quot;,false))));

For each Map.of you would need to pass that to a Map implementation if you want them all to be mutable.

huangapple
  • 本文由 发表于 2020年8月1日 05:23:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63199251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定