What is the use of Map.ofEntries() instead of Map.of()

后端 未结 3 1240
深忆病人
深忆病人 2020-12-05 15:14

From the documentation of Map.java -

The Map.of() and Map.ofEntries() static factory methods provide a convenient way to cre

3条回答
  •  一生所求
    2020-12-05 16:15

    Java 9 introduced creating small unmodifiable Collection instances using a concise one line code, for maps the signature of factory method is:

    static  Map of(K k1, V v1, K k2, V v2, K k3, V v3)
    

    This method is overloaded to have 0 to 10 key-value pairs, e.g.

    Map map = Map.of("1", "first");
    Map map = Map.of("1", "first", "2", "second");
    Map map = Map.of("1", "first", "2", "second", "3", "third");
    

    Similarly you can have up to ten entries.

    For a case where we have more than 10 key-value pairs, there is a different method:

    static  Map ofEntries(Map.Entry... entries)
    

    Here is the usage.

    Map map = Map.ofEntries(
      new AbstractMap.SimpleEntry<>("1", "first"),
      new AbstractMap.SimpleEntry<>("2", "second"),
      new AbstractMap.SimpleEntry<>("3", "third"));
    

提交回复
热议问题