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.
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);
java9
Map<Integer, String> 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<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"); } });
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!