adding multiple entries to a HashMap at once in one statement

前端 未结 9 962
迷失自我
迷失自我 2020-12-04 06:27

I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this:

  hashMap.put(\"One\", new Integer(1)); // add         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 06:55

    Since Java 9, it is possible to use Map.of(...), like so:

    Map immutableMap = Map.of("One", 1, 
                                               "Two", 2, 
                                               "Three", 3);
    

    This map is immutable. If you want the map to be mutable, you have to add:

    Map hashMap = new HashMap<>(immutableMap);
    

    If you can't use Java 9, you're stuck with writing a similar helper method yourself or using a third-party library (like Guava) to add that functionality for you.

提交回复
热议问题