adding multiple entries to a HashMap at once in one statement

前端 未结 9 966
迷失自我
迷失自我 2020-12-04 06:27

I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this:

  hashMap.put(\"One\", new Integer(1)); // add         


        
9条回答
  •  抹茶落季
    2020-12-04 06:46

    You can use Google Guava's ImmutableMap. This works as long as you don't care about modifying the Map later (you can't call .put() on the map after constructing it using this method):

    import com.google.common.collect.ImmutableMap;
    
    // For up to five entries, use .of()
    Map littleMap = ImmutableMap.of(
        "One", Integer.valueOf(1),
        "Two", Integer.valueOf(2),
        "Three", Integer.valueOf(3)
    );
    
    // For more than five entries, use .builder()
    Map bigMap = ImmutableMap.builder()
        .put("One", Integer.valueOf(1))
        .put("Two", Integer.valueOf(2))
        .put("Three", Integer.valueOf(3))
        .put("Four", Integer.valueOf(4))
        .put("Five", Integer.valueOf(5))
        .put("Six", Integer.valueOf(6))
        .build();
    

    See also: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html

    A somewhat related question: ImmutableMap.of() workaround for HashMap in Maps?

提交回复
热议问题