Home > Java > javaTutorial > body text

One trick to teach you how to quickly create a Map using Java (code sharing)

奋力向前
Release: 2021-09-14 13:19:15
forward
10336 people have browsed it

In the previous article "Understanding the new java.util.function.*pojo reflection method in java8 (with code)", we learned about the new pojo reflection method in java8. The following article will introduce to you how to use java to quickly create a Map. Let's see how to do it together.

One trick to teach you how to quickly create a Map using Java (code sharing)

If you want to quickly create a Map without frequent new, the fastest way is to use Guava , use ImmutableMap.of("a", 1, "b", 2, "c", 3);

Guava

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

java9

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

More than 10 groups will not be supported, so it will be like this:

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 )
);
Copy after login

Anonymous

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");
            }
        });
Copy after login

Recommended learning: Java video tutorial

The above is the detailed content of One trick to teach you how to quickly create a Map using Java (code sharing). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:chuchur.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!