How can I initialise a static Map?

前端 未结 30 1530
慢半拍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:27

    With Java 8 I've come to use the following pattern:

    private static final Map MAP = Stream.of(
        new AbstractMap.SimpleImmutableEntry<>("key1", 1),
        new AbstractMap.SimpleImmutableEntry<>("key2", 2)
    ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    

    It's not the most terse and a bit roundabout, but

    • it doesn't require anything outside of java.util
    • it's typesafe and easily accommodates different types for key and value.

提交回复
热议问题