如何使用java快速创建Map

今天就跟大家聊聊有关如何使用java快速创建Map,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

想要快速创建Map,不用频繁new,最快的方法就是用Guava,使用ImmutableMap.of("a", 1, "b", 2, "c", 3);

Guava

Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);

java9

Map<Integer, String> map = Map.of(1, "A", 2, "B", 3, "C");

超过 10 组会不支持,那么就要这样:

Map.ofEntries(
    Map.entry( 1, false ),
    Map.entry( 2, true ),
    Map.entry( 3, false ),
    Map.entry( 4, true ),
    Map.entry( 5, false ),
    Map.entry( 6, true ),
    Map.entry( 7, false ),
    Map.entry( 8, true ),
    Map.entry( 9, false ),
    Map.entry( 10, true ),
    Map.entry( 11, false )
);

匿名

Map<Integer, String> mymap = new HashMap<Integer, String>() {
	{
		put(1, "one");
		put(2, "two");
	}
};
Collections.unmodifiableMap(new HashMap<Integer, String>() {
            {
                put(0, "zero");
                put(1, "one");
                put(2, "two");
                put(3, "three");
                put(4, "four");
                put(5, "five");
                put(6, "six");
                put(7, "seven");
                put(8, "eight");
                put(9, "nine");
                put(10, "ten");
                put(11, "eleven");
                put(12, "twelve");
            }
        });

看完上述内容,你们对如何使用java快速创建Map有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。