Map的快速构建

"你们还在用new吗?"

Posted by Ariescat on September 4, 2020

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

  • Guava

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

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

喜迎
春节