Is there a best practice for writing maps literal style in Java?

前端 未结 9 1659
感情败类
感情败类 2020-12-24 03:03

In short, if you want to write a map of e.g. constants in Java, which in e.g. Python and Javascript you would write as a literal,

T CON         


        
相关标签:
9条回答
  • 2020-12-24 03:36

    Ok, with Jorn's improvement I can't seem to change the map at all, internally or externally. Perhaps not quite as readable, but if you need the map to be unmodifiable I think this is better.

    public class MapTest {
        private static Map<String, String> map = initMap();
    
        private static Map<String, String> initMap() {
            Map<String, String> map = new HashMap<String, String>();
    
            map.put("A", "Apple");
            map.put("B", "Banana");
            // etc
            return Collections.unmodifiableMap(map);
        }
    
        public Map<String, String> getMap() {
            return map;
        }
    
        public static void main(String[] args) {
            MapTest m = new MapTest();
            System.out.println(m.getMap().get("A"));
            m.getMap().put("this", "that");
        }
    }
    
    0 讨论(0)
  • 2020-12-24 03:37

    I like to do it this way:

    Map map = new HashMap() {{
        put("foo", "bar");
        put(123, 456);
    }};
    

    The double {{ }} are an instance initialization block. They are a bit unusual but they are useful. No need for libraries or helpers.

    0 讨论(0)
  • 2020-12-24 03:37

    Java7 suppose to implement following syntax:

    Map<String, String> = {
        "key1": "value",
        "key2": "value",
        "key3": "value",
        "key4": "value"
    };
    

    However now you're forced to use solutions proposed by Jorn or Tony Ennis.

    0 讨论(0)
  • 2020-12-24 03:43

    You can write yourself a quick helper function:

    @SuppressWarnings("unchecked")
    public static <K,V> Map<K,V> ImmutableMap(Object... keyValPair){
        Map<K,V> map = new HashMap<K,V>();
    
        if(keyValPair.length % 2 != 0){
            throw new IllegalArgumentException("Keys and values must be pairs.");
        }
    
        for(int i = 0; i < keyValPair.length; i += 2){
            map.put((K) keyValPair[i], (V) keyValPair[i+1]);
        }
    
        return Collections.unmodifiableMap(map);
    }
    

    Note the code above isn't going to stop you from overwriting constants of the same name, using CONST_1 multiple places in your list will result in the final CONST_1's value appearing.

    Usage is something like:

    Map<String,Double> constants = ImmutableMap(
        "CONST_0", 1.0,
        "CONST_1", 2.0
    );
    
    0 讨论(0)
  • 2020-12-24 03:45

    Constants? I'd use an enum.

    public enum Constants { 
        NAME_1("Value1"),
        NAME_2("Value2"),
        NAME_3("Value3");
    
        private String value;
    
        Constants(String value) {
            this.value = value;
        }
    
        public String value() {
            return value;
        }
    }
    

    Value for e.g. NAME_2 can be obtained as follows:

    String name2value = Constants.NAME_2.value();
    

    Only give the enum a bit more sensible name, e.g. Settings, Defaults, etc, whatever those name/value pairs actually represent.

    0 讨论(0)
  • 2020-12-24 03:51

    Here's another way, best suited for maps that won't be changing:

    public class Whatever {
        private static Map<String,String> map = new HashMap<String,String>();
    
        static {
            map.put("A", "Apple");
            map.put("B", "Banana");
            // etc
        }
    }
    
    0 讨论(0)
提交回复
热议问题