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

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

奋力向前
奋力向前 forward
2021-09-14 13:19:15 10328browse

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 aMapwithout frequentnew, the fastest way is to useGuava, useImmutableMap.of("a", 1, "b", 2, "c", 3);

Guava

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

java9

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

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 ) );

Anonymous

Map mymap = new HashMap() { { put(1, "one"); put(2, "two"); } }; Collections.unmodifiableMap(new HashMap() { { 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"); } });

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!

Statement:
This article is reproduced at:chuchur.com. If there is any infringement, please contact admin@php.cn delete