builder for HashMap

前端 未结 15 2243
迷失自我
迷失自我 2020-11-30 00:17

Guava provides us with great factory methods for Java types, such as Maps.newHashMap().

But are there also builders for java Maps?

HashM         


        
15条回答
  •  既然无缘
    2020-11-30 00:48

    Since Java 9 Map interface contains:

    • Map.of(k1,v1, k2,v2, ..)
    • Map.ofEntries(Map.entry(k1,v1), Map.entry(k2,v2), ..).

    Limitations of those factory methods are that they:

    • can't hold nulls as keys and/or values (if you need to store nulls take a look at other answers)
    • produce immutable maps

    If we need mutable map (like HashMap) we can use its copy-constructor and let it copy content of map created via Map.of(..)

    Map map = new HashMap<>( Map.of(1,"a", 2,"b", 3,"c") );
    

提交回复
热议问题