How can I initialise a static Map?

前端 未结 30 1753
慢半拍i
慢半拍i 2020-11-22 08:43

How would you initialise a static Map in Java?

Method one: static initialiser
Method two: instance initialiser (anonymous subclass) or some other m

30条回答
  •  忘掉有多难
    2020-11-22 09:39

    Here's a Java 8 one-line static map initializer:

    private static final Map EXTENSION_TO_MIMETYPE =
        Arrays.stream(new String[][] {
            { "txt", "text/plain" }, 
            { "html", "text/html" }, 
            { "js", "application/javascript" },
            { "css", "text/css" },
            { "xml", "application/xml" },
            { "png", "image/png" }, 
            { "gif", "image/gif" }, 
            { "jpg", "image/jpeg" },
            { "jpeg", "image/jpeg" }, 
            { "svg", "image/svg+xml" },
        }).collect(Collectors.toMap(kv -> kv[0], kv -> kv[1]));
    

    Edit: to initialize a Map as in the question, you'd need something like this:

    static final Map MY_MAP = Arrays.stream(new Object[][]{
            {1, "one"},
            {2, "two"},
    }).collect(Collectors.toMap(kv -> (Integer) kv[0], kv -> (String) kv[1]));
    

    Edit(2): There is a better, mixed-type-capable version by i_am_zero that uses a stream of new SimpleEntry<>(k, v) calls. Check out that answer: https://stackoverflow.com/a/37384773/3950982

提交回复
热议问题