原来路径:https://www.itranslater.com/qa/details/2104117160695038976
java – 如何初始化静态Map?
import com.google.common.collect.ImmutableMap;
import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Auther: Liruilong
* @Date: 2020/7/25 13:40
* @Description:
*/
public class test {
// 静态Map的初始化,实际情况中,可以使用枚举代替
// 方法一
public static final Map<Integer, String> myMap_0 = new HashMap<Integer, String>();
static {
myMap_0.put(1, "one");
myMap_0.put(2, "two");
}
// 方法二 JDK5
public static final Map<Integer, String> myMap_1 = new HashMap<Integer, String>() {{
put(1, "one");
put(2, "two");
}};
// 方法三 Guava
static final Map<Integer,String> myMap_2 = ImmutableMap.<Integer, String> builder().put(1, "one").put(2, "two").build();
// 方法四,不超过5个的时候 Guava
static final Map<Integer, String> myMap_3 = ImmutableMap.of(
1, "one",
2, "two"
);
// 方法五 Collections.unmodifiableMap() 通过工具类实现
// 方法六 JDK8
static final Map<Integer, String> MY_MAP = Arrays.stream(new Object[][]{
{1, "one"},
{2, "two"},
}).collect(Collectors.toMap(kv -> (Integer) kv[0], kv -> (String) kv[1]));
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));
}