Java 静态(static) Map字典初始化方法及示例代码

本文主要介绍Java中,初始化static静态的Map(HashMap)字典的方法,以及相关的示例代码。

1、使用静态代码块初始化

public class Test {
    private static final Map<Integer, String> myMap;
    static {
        Map<Integer, String> aMap = HashMap<Integer, String>();
        aMap.put(1, "one");
        aMap.put(2, "two");
        myMap = Collections.unmodifiableMap(aMap);
    }
}

2、使用static静态方法初始化

public class Test {
    private static final Map<Integer, String> MY_MAP = createMap();
    private static Map<Integer, String> createMap() {
        Map<Integer, String> result = new HashMap<>();
        result.put(1, "one");
        result.put(2, "two");
        return Collections.unmodifiableMap(result);
    }
}

3、使用Map.ofEntries初始化(Java 9+)

文档:

Map.ofEntries

Map.entry( k , v )

import static java.util.Map.entry;
private static final Map<Integer,String> map = Map.ofEntries(
        entry(1, "one"),
        entry(2, "two"),
        entry(3, "three"),
        entry(4, "four"),
        entry(5, "five"),
        entry(6, "six"),
        entry(7, "seven"),
        entry(8, "eight"),
        entry(9, "nine"),
        entry(10, "ten"));

4、使用Stream.of()和SimpleImmutableEntry初始化(Java 8+)

文档

SimpleEntry

SimpleImmutableEntry

import java.util.AbstractMap.*;
private static final Map<Integer, String> myMap = Stream.of(
            new SimpleEntry<>(1, "one"),
            new SimpleEntry<>(2, "two"),
            new SimpleEntry<>(3, "three"),
            new SimpleEntry<>(4, "four"),
            new SimpleEntry<>(5, "five"),
            new SimpleEntry<>(6, "six"),
            new SimpleEntry<>(7, "seven"),
            new SimpleEntry<>(8, "eight"),
            new SimpleEntry<>(9, "nine"),
            new SimpleEntry<>(10, "ten"))
            .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));

5、使用Map.of实现静态Map初始化(Java 9+)

private static final Map<Integer, String> MY_MAP = Map.of(1, "one", 2, "two");

相关文档:

java中 static final修饰Hashmap静态成员变量初始化方法

java使用Hashmap中的数据初始化Hashmap并执行put数据的简洁代码


推荐阅读
cjavapy编程之路首页