Search code examples
javahashmapmapsimmutabilitymutable

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)));

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


Solution

  • 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.