adding multiple entries to a HashMap at once in one statement

前端 未结 9 961
迷失自我
迷失自我 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:52

    Here's a simple class that will accomplish what you want

    import java.util.HashMap;
    
    public class QuickHash extends HashMap<String,String> {
        public QuickHash(String...KeyValuePairs) {
            super(KeyValuePairs.length/2);
            for(int i=0;i<KeyValuePairs.length;i+=2)
                put(KeyValuePairs[i], KeyValuePairs[i+1]);
        }
    }
    

    And then to use it

    Map<String, String> Foo=QuickHash(
        "a", "1",
        "b", "2"
    );
    

    This yields {a:1, b:2}

    0 讨论(0)
  • 2020-12-04 06:55

    Since Java 9, it is possible to use Map.of(...), like so:

    Map<String, Integer> immutableMap = Map.of("One", 1, 
                                               "Two", 2, 
                                               "Three", 3);
    

    This map is immutable. If you want the map to be mutable, you have to add:

    Map<String, Integer> hashMap = new HashMap<>(immutableMap);
    

    If you can't use Java 9, you're stuck with writing a similar helper method yourself or using a third-party library (like Guava) to add that functionality for you.

    0 讨论(0)
  • 2020-12-04 06:58

    You can use the Double Brace Initialization as shown below:

    Map<String, Integer> hashMap = new HashMap<String, Integer>()
    {{
         put("One", 1);
         put("Two", 2);
         put("Three", 3);
    }};
    

    As a piece of warning, please refer to the thread Efficiency of Java “Double Brace Initialization" for the performance implications that it might have.

    0 讨论(0)
提交回复
热议问题