Java9 集合工厂方法(3)

以下工厂方法则添加到Map接口中:

static <K,V> Map<K,V> of() static <K,V> Map<K,V> of(K k1, V v1) static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2) static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3) static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)

第一个方法创建了一个空的不可变的Map,接下来10个方法创建包含1-10和键值对的Map,尽管这些方法比较混乱,但它们避免了final类型的可变参方法产生的数组分配,初始化和垃圾回收开销,且支持任意大小的Map。

虽然Map的可变参数方法近似List和Set的,但是它的每个键值对必须被包装起来,下面这个方法可以方便地将包装键值对转换为Map标准键值对:

Map.Entry<K,V> entry(K k, V v)

下面是Map的ofEntries() 和entry()方法的示例:

import java.util.Map; import static java.util.Map.entry; public class MapDemo { public static void main(String[] args) { Map<String, String> capCities = Map.ofEntries(entry("Manitoba", "Winnipeg"), entry("Alberta", "Edmonton")); capCities.forEach((k, v) -> System.out.printf("Key = %s, Value = %s%n", k, v)); try { capCities.put("British Columbia", "Victoria"); } catch (UnsupportedOperationException uoe) { System.err.println("unable to modify capCities map"); } } }

运行后输出:

Key = Alberta, Value = Edmonton Key = Manitoba, Value = Winnipeg unable to modify capCities map

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/e4d422ab36c95ab55b5212cef8f746bb.html