Better Map Constructor

后端 未结 5 648
走了就别回头了
走了就别回头了 2021-01-02 10:13

Is there a more streamlined way to do the following?

Map map = new HashMap();
map.put(\"a\", \"apple\");
map.put(         


        
5条回答
  •  感情败类
    2021-01-02 10:38

    Java 9 adds Map.of, such as:

    Map map = Map.of("a", "apple", "b", "bear", "c", "cat");
    

    Up to 10 entries are supported. For more entries you can use the overload taking Entry:

    Map map 
        = Map.ofEntries
            (Map.entry("a", "apple")
            , Map.entry("b", "bear")
            , Map.entry("c", "cat"));
    

    Note that these methods do not return a HashMap. It returns an optimized immutable map.

提交回复
热议问题