How to directly initialize a HashMap (in a literal way)?

后端 未结 14 2381
野趣味
野趣味 2020-11-22 10:58

Is there some way of initializing a Java HashMap like this?:

Map test = 
    new HashMap{\"test\":\"test\",\"test\         


        
相关标签:
14条回答
  • 2020-11-22 11:16

    You can create a method to initialize the map like in this example below:

    Map<String, Integer> initializeMap()
    {
      Map<String, Integer> ret = new HashMap<>();
    
      //populate ret
      ...
    
      return ret;
    }
    
    //call
    Map<String, Integer> map = initializeMap();
    
    0 讨论(0)
  • 2020-11-22 11:25

    There is no direct way to do this - Java has no Map literals (yet - I think they were proposed for Java 8).

    Some people like this:

    Map<String,String> test = new HashMap<String, String>(){{
           put("test","test"); put("test","test");}};
    

    This creates an anonymous subclass of HashMap, whose instance initializer puts these values. (By the way, a map can't contain twice the same value, your second put will overwrite the first one. I'll use different values for the next examples.)

    The normal way would be this (for a local variable):

    Map<String,String> test = new HashMap<String, String>();
    test.put("test","test");
    test.put("test1","test2");
    

    If your test map is an instance variable, put the initialization in a constructor or instance initializer:

    Map<String,String> test = new HashMap<String, String>();
    {
        test.put("test","test");
        test.put("test1","test2");
    }
    

    If your test map is a class variable, put the initialization in a static initializer:

    static Map<String,String> test = new HashMap<String, String>();
    static {
        test.put("test","test");
        test.put("test1","test2");
    }
    

    If you want your map to never change, you should after the initialization wrap your map by Collections.unmodifiableMap(...). You can do this in a static initializer too:

    static Map<String,String> test;
    {
        Map<String,String> temp = new HashMap<String, String>();
        temp.put("test","test");
        temp.put("test1","test2");
        test = Collections.unmodifiableMap(temp);
    }
    

    (I'm not sure if you can now make test final ... try it out and report here.)

    0 讨论(0)
  • 2020-11-22 11:29

    JAVA 8

    In plain java 8 you also have the possibility of using Streams/Collectors to do the job.

    Map<String, String> myMap = Stream.of(
             new SimpleEntry<>("key1", "value1"),
             new SimpleEntry<>("key2", "value2"),
             new SimpleEntry<>("key3", "value3"))
            .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));
    

    This has the advantage of not creating an Anonymous class.

    Note that the imports are:

    import static java.util.stream.Collectors.toMap;
    import java.util.AbstractMap.SimpleEntry;
    

    Of course, as noted in other answers, in java 9 onwards you have simpler ways of doing the same.

    0 讨论(0)
  • 2020-11-22 11:31

    An alternative, using plain Java 7 classes and varargs: create a class HashMapBuilder with this method:

    public static HashMap<String, String> build(String... data){
        HashMap<String, String> result = new HashMap<String, String>();
    
        if(data.length % 2 != 0) 
            throw new IllegalArgumentException("Odd number of arguments");      
    
        String key = null;
        Integer step = -1;
    
        for(String value : data){
            step++;
            switch(step % 2){
            case 0: 
                if(value == null)
                    throw new IllegalArgumentException("Null key value"); 
                key = value;
                continue;
            case 1:             
                result.put(key, value);
                break;
            }
        }
    
        return result;
    }
    

    Use the method like this:

    HashMap<String,String> data = HashMapBuilder.build("key1","value1","key2","value2");
    
    0 讨论(0)
  • 2020-11-22 11:32

    If you need to place only one key-value pair, you can use Collections.singletonMap(key, value);

    0 讨论(0)
  • 2020-11-22 11:34
    Map<String,String> test = new HashMap<String, String>()
    {
        {
            put(key1, value1);
            put(key2, value2);
        }
    };
    
    0 讨论(0)
提交回复
热议问题