Wondercease

浙ICP备2022017321号

Java HashMap对象创建时初始化

1、使用Collections.singletonMap()初始化

Collections.singletonMap()可以为HashMap初始一个key和value。

2、Map.of()或Map.ofEntries()

Java 9及以上版本,可以使用Map.of()或Map.ofEntries()对HashMap对象进行初始化。

1)最多适用于10个元素

importjava.util.*;

publicclassMain{

publicstaticvoidmain(String[] args){

Map m1 = Map.of(

“C”,”cjavapy”,

“Java”,”code”

);

System.out.println(m1);

System.exit(0);//success

}

}

2)适用于任何数量的元素

importjava.util.*;

importstaticjava.util.Map.entry;

publicclassMain{

publicstaticvoidmain(String[] args){

Map m2 = Map.ofEntries(

entry(“C”,”cjavapy”),

entry(“Java”,”code”)

);

System.out.println(m2);

System.exit(0);//success

}

}

3、使用初始化器

Java 8及以上版本,可以在匿名子类中使用初始化器来实现。

import java.util.*;

public class Main {
public static void main(String[] args) {
Map m1 = new HashMap() {{
put("C", "cjavapy");
put("Java", "code");
}};
System.out.println(m1);
System.exit(0); //success
}}

4、 ImmutableMap.of()

可以使用ImmutableMap.of()指定初始化的key和value

5、Stream.of()

Map m1 = Stream.of(
new SimpleEntry<>("key1", "value1"),
new SimpleEntry<>("key2", "value2"),
new SimpleEntry<>("key3", "value3"))
.collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));

发表评论

您的电子邮箱地址不会被公开。